PowerShell/docs/convert-dir27z.md
2025-05-12 22:04:02 +02:00

2.8 KiB

The convert-dir27z.ps1 Script

This PowerShell script compresses the given directory (including subfolders) into a compressed .7z file. It also preserves symbolic links and requires that 7-zip is installed.

Parameters

/Repos/PowerShell/scripts/convert-dir27z.ps1 [[-dirPath] <String>] [[-targetFile] <String>] [<CommonParameters>]

-dirPath <String>
    Specifies the path to the directory (to be entered by default)
    
    Required?                    false
    Position?                    1
    Default value                
    Accept pipeline input?       false
    Aliases                      
    Accept wildcard characters?  false

-targetFile <String>
    Specifies the path to the target file (<dirPath>.7z by default)
    
    Required?                    false
    Position?                    2
    Default value                
    Accept pipeline input?       false
    Aliases                      
    Accept wildcard characters?  false

[<CommonParameters>]
    This script supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, 
    WarningVariable, OutBuffer, PipelineVariable, and OutVariable.

Example

PS> ./convert-dir27z.ps1 C:\Windows Win.7z
 Converted 📂C:\Windows into Win.7z in 291s.

Notes

Author: Markus Fleschutz | License: CC0

https://github.com/fleschutz/PowerShell

Script Content

<#
.SYNOPSIS
	Converts a directory into a .7z file
.DESCRIPTION
	This PowerShell script compresses the given directory (including subfolders) into a compressed .7z file.
	It also preserves symbolic links and requires that 7-zip is installed.
.PARAMETER dirPath
	Specifies the path to the directory (to be entered by default)
.PARAMETER targetFile
	Specifies the path to the target file (<dirPath>.7z by default)
.EXAMPLE
	PS> ./convert-dir27z.ps1 C:\Windows Win.7z
	✅ Converted 📂C:\Windows into Win.7z in 291s.
.LINK
	https://github.com/fleschutz/PowerShell
.NOTES
	Author: Markus Fleschutz | License: CC0
#>

param([string]$dirPath = "", [string]$targetFile = "")

try {
	if (-not(Test-Path "C:\Program Files\7-Zip\7z.exe" -pathType leaf)) { throw "Please install 7-Zip" }
	if ($dirPath -eq "" ) { $dirPath = Read-Host "Enter the path to the folder" }

	$stopWatch = [system.diagnostics.stopwatch]::startNew()
	$dirPath = Resolve-Path $dirPath
	if ($targetFile -eq "" ) { $targetFile = "$dirPath.7z" }

	& "C:\Program Files\7-Zip\7z.exe" a -y -snl -t7z $targetFile $dirPath

	[int]$elapsed = $stopWatch.Elapsed.TotalSeconds
	"✅ Converted 📂$dirPath into $targetFile in $($elapsed)s."
	exit 0 # success
} catch {
	"⚠️ Error in line $($_.InvocationInfo.ScriptLineNumber): $($Error[0])"
	exit 1
}

(page generated by convert-ps2md.ps1 as of 05/12/2025 22:02:53)