opt/opt.ps1
if ($PSVersionTable.PSVersion.Major -lt 5) { <# Copied from the Microsoft Module: Microsoft.PowerShell.Archive Which ships with PowerShell Version 5 but will run under v3. #> function Compress-Archive { <# .SYNOPSIS Creates an archive, or zipped file, from specified files and folders. .DESCRIPTION The Compress-Archive cmdlet creates a zipped (or compressed) archive file from one or more specified files or folders. An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage. An archive file can be compressed by using the compression algorithm specified by the CompressionLevel parameter. Because Compress-Archive relies upon the Microsoft .NET Framework API System.IO.Compression.ZipArchive to compress files, the maximum file size that you can compress by using Compress-Archive is currently 2 GB. This is a limitation of the underlying API. .PARAMETER Path Specifies the path or paths to the files that you want to add to the archive zipped file. This parameter can accept wildcard characters. Wildcard characters allow you to add all files in a folder to your zipped archive file. To specify multiple paths, and include files in multiple locations in your output zipped file, use commas to separate the paths. .PARAMETER LiteralPath Specifies the path or paths to the files that you want to add to the archive zipped file. Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose each escape character in single quotation marks, to instruct Windows PowerShell not to interpret any characters as escape sequences. To specify multiple paths, and include files in multiple locations in your output zipped file, use commas to separate the paths. .PARAMETER DestinationPath Specifies the path to the archive output file. This parameter is required. The specified DestinationPath value should include the desired name of the output zipped file; it specifies either the absolute or relative path to the zipped file. If the file name specified in DestinationPath does not have a .zip file name extension, the cmdlet adds a .zip file name extension. .PARAMETER CompressionLevel Specifies how much compression to apply when you are creating the archive file. Faster compression requires less time to create the file, but can result in larger file sizes. The acceptable values for this parameter are: - Fastest. Use the fastest compression method available to decrease processing time; this can result in larger file sizes. - NoCompression. Do not compress the source files. - Optimal. Processing time is dependent on file size. If this parameter is not specified, the command uses the default value, Optimal. .PARAMETER Update Updates the specified archive by replacing older versions of files in the archive with newer versions of files that have the same names. You can also add this parameter to add files to an existing archive. .PARAMETER Force @{Text=} .PARAMETER Confirm Prompts you for confirmation before running the cmdlet. .PARAMETER WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. .EXAMPLE Example 1: Create an archive file PS C:\>Compress-Archive -LiteralPath C:\Reference\Draftdoc.docx, C:\Reference\Images\diagram2.vsd -CompressionLevel Optimal -DestinationPath C:\Archives\Draft.Zip This command creates a new archive file, Draft.zip, by compressing two files, Draftdoc.docx and diagram2.vsd, specified by the LiteralPath parameter. The compression level specified for this operation is Optimal. .EXAMPLE Example 2: Create an archive with wildcard characters PS C:\>Compress-Archive -Path C:\Reference\* -CompressionLevel Fastest -DestinationPath C:\Archives\Draft This command creates a new archive file, Draft.zip, in the C:\Archives folder. Note that though the file name extension .zip was not added to the value of the DestinationPath parameter, Windows PowerShell appends this to the specified archive file name automatically. The new archive file contains every file in the C:\Reference folder, because a wildcard character was used in place of specific file names in the Path parameter. The specified compression level is Fastest, which might result in a larger output file, but compresses a large number of files faster. .EXAMPLE Example 3: Update an existing archive file PS C:\>Compress-Archive -Path C:\Reference\* -Update -DestinationPath C:\Archives\Draft.Zip This command updates an existing archive file, Draft.Zip, in the C:\Archives folder. The command is run to update Draft.Zip with newer versions of existing files that came from the C:\Reference folder, and also to add new files that have been added to C:\Reference since Draft.Zip was initially created. .EXAMPLE Example 4: Create an archive from an entire folder PS C:\>Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft This command creates an archive from an entire folder, C:\Reference. Note that though the file name extension .zip was not added to the value of the DestinationPath parameter, Windows PowerShell appends this to the specified archive file name automatically. #> [CmdletBinding(DefaultParameterSetName = "Path", SupportsShouldProcess, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=393252")] param ( [parameter (Mandatory, ParameterSetName = "Path", ValueFromPipeline, ValueFromPipelineByPropertyName)] [parameter (Mandatory, ParameterSetName = "PathWithForce", ValueFromPipeline, ValueFromPipelineByPropertyName)] [parameter (Mandatory, ParameterSetName = "PathWithUpdate", ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [string[]] $Path, [parameter (Mandatory, ParameterSetName = "LiteralPath", ValueFromPipeline = $false, ValueFromPipelineByPropertyName)] [parameter (Mandatory, ParameterSetName = "LiteralPathWithForce", ValueFromPipeline = $false, ValueFromPipelineByPropertyName)] [parameter (Mandatory, ParameterSetName = "LiteralPathWithUpdate", ValueFromPipeline = $false, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [string[]] $LiteralPath, [parameter (Mandatory, Position = 1, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [ValidateNotNullOrEmpty()] [string] $DestinationPath, [parameter ( mandatory = $false, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [ValidateSet("Optimal", "NoCompression", "Fastest")] [string] $CompressionLevel = "Optimal", [parameter(Mandatory, ParameterSetName = "PathWithUpdate", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [parameter(Mandatory, ParameterSetName = "LiteralPathWithUpdate", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [switch] $Update = $false, [parameter(Mandatory, ParameterSetName = "PathWithForce", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [parameter(Mandatory, ParameterSetName = "LiteralPathWithForce", ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [switch] $Force = $false ) BEGIN { Add-Type -AssemblyName System.IO.Compression -ErrorAction Ignore Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Ignore $zipFileExtension = ".zip" $LocalizedData = ConvertFrom-StringData @' PathNotFoundError=The path '{0}' either does not exist or is not a valid file system path. ExpandArchiveInValidDestinationPath=The path '{0}' is not a valid file system directory path. InvalidZipFileExtensionError={0} is not a supported archive file format. {1} is the only supported archive file format. ArchiveFileIsReadOnly=The attributes of the archive file {0} is set to 'ReadOnly' hence it cannot be updated. If you intend to update the existing archive file, remove the 'ReadOnly' attribute on the archive file else use -Force parameter to override and create a new archive file. ZipFileExistError=The archive file {0} already exists. Use the -Update parameter to update the existing archive file or use the -Force parameter to overwrite the existing archive file. DuplicatePathFoundError=The input to {0} parameter contains a duplicate path '{1}'. Provide a unique set of paths as input to {2} parameter. ArchiveFileIsEmpty=The archive file {0} is empty. CompressProgressBarText=The archive file '{0}' creation is in progress... ExpandProgressBarText=The archive file '{0}' expansion is in progress... AppendArchiveFileExtensionMessage=The archive file path '{0}' supplied to the DestinationPath patameter does not include .zip extension. Hence .zip is appended to the supplied DestinationPath path and the archive file would be created at '{1}'. AddItemtoArchiveFile=Adding '{0}'. CreateFileAtExpandedPath=Created '{0}'. InvalidArchiveFilePathError=The archive file path '{0}' specified as input to the {1} parameter is resolving to multiple file system paths. Provide a unique path to the {2} parameter where the archive file has to be created. InvalidExpandedDirPathError=The directory path '{0}' specified as input to the DestinationPath parameter is resolving to multiple file system paths. Provide a unique path to the Destination parameter where the archive file contents have to be expanded. FileExistsError=Failed to create file '{0}' while expanding the archive file '{1}' contents as the file '{2}' already exists. Use the -Force parameter if you want to overwrite the existing directory '{3}' contents when expanding the archive file. DeleteArchiveFile=The partially created archive file '{0}' is deleted as it is not usable. InvalidDestinationPath=The destination path '{0}' does not contain a valid archive file name. PreparingToCompressVerboseMessage=Preparing to compress... PreparingToExpandVerboseMessage=Preparing to expand... '@ #region Utility Functions function GetResolvedPathHelper { param ( [string[]] $path, [boolean] $isLiteralPath, [System.Management.Automation.PSCmdlet] $callerPSCmdlet ) $resolvedPaths = @() # null and empty check are are already done on Path parameter at the cmdlet layer. foreach ($currentPath in $path) { try { if ($isLiteralPath) { $currentResolvedPaths = Resolve-Path -LiteralPath $currentPath -ErrorAction Stop } else { $currentResolvedPaths = Resolve-Path -Path $currentPath -ErrorAction Stop } } catch { $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath) $exception = New-Object System.InvalidOperationException $errorMessage, $_.Exception $errorRecord = CreateErrorRecordHelper "ArchiveCmdletPathNotFound" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $currentPath $callerPSCmdlet.ThrowTerminatingError($errorRecord) } foreach ($currentResolvedPath in $currentResolvedPaths) { $resolvedPaths += $currentResolvedPath.ProviderPath } } $resolvedPaths } function Add-CompressionAssemblies { if ($PSEdition -eq "Desktop") { Add-Type -AssemblyName System.IO.Compression Add-Type -AssemblyName System.IO.Compression.FileSystem } } function IsValidFileSystemPath { param ( [string[]] $path ) $result = $true; # null and empty check are are already done on Path parameter at the cmdlet layer. foreach ($currentPath in $path) { if (!([System.IO.File]::Exists($currentPath) -or [System.IO.Directory]::Exists($currentPath))) { $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath) ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath } } return $result; } function ValidateDuplicateFileSystemPath { param ( [string] $inputParameter, [string[]] $path ) $uniqueInputPaths = @() # null and empty check are are already done on Path parameter at the cmdlet layer. foreach ($currentPath in $path) { $currentInputPath = $currentPath.ToUpper() if ($uniqueInputPaths.Contains($currentInputPath)) { $errorMessage = ($LocalizedData.DuplicatePathFoundError -f $inputParameter, $currentPath, $inputParameter) ThrowTerminatingErrorHelper "DuplicatePathFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath } else { $uniqueInputPaths += $currentInputPath } } } function CompressionLevelMapper { param ( [string] $compressionLevel ) $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Optimal # CompressionLevel format is already validated at the cmdlet layer. switch ($compressionLevel.ToString()) { "Fastest" { $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Fastest } "NoCompression" { $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::NoCompression } } return $compressionLevelFormat } function CompressArchiveHelper { param ( [string[]] $sourcePath, [string] $destinationPath, [string] $compressionLevel, [bool] $isUpdateMode ) $numberOfItemsArchived = 0 $sourceFilePaths = @() $sourceDirPaths = @() foreach ($currentPath in $sourcePath) { $result = Test-Path -LiteralPath $currentPath -PathType Leaf if ($result -eq $true) { $sourceFilePaths += $currentPath } else { $sourceDirPaths += $currentPath } } # The Soure Path contains one or more directory (this directory can have files under it) and no files to be compressed. if ($sourceFilePaths.Count -eq 0 -and $sourceDirPaths.Count -gt 0) { $currentSegmentWeight = 100 / [double]$sourceDirPaths.Count $previousSegmentWeight = 0 foreach ($currentSourceDirPath in $sourceDirPaths) { $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight $numberOfItemsArchived += $count $previousSegmentWeight += $currentSegmentWeight } } # The Soure Path contains only files to be compressed. elseIf ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -eq 0) { # $previousSegmentWeight is equal to 0 as there are no prior segments. # $currentSegmentWeight is set to 100 as all files have equal weightage. $previousSegmentWeight = 0 $currentSegmentWeight = 100 $numberOfItemsArchived = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight } # The Soure Path contains one or more files and one or more directories (this directory can have files under it) to be compressed. elseif ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -gt 0) { # each directory is considered as an individual segments & all the individual files are clubed in to a separate sgemnet. $currentSegmentWeight = 100 / [double]($sourceDirPaths.Count + 1) $previousSegmentWeight = 0 foreach ($currentSourceDirPath in $sourceDirPaths) { $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight $numberOfItemsArchived += $count $previousSegmentWeight += $currentSegmentWeight } $count = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight $numberOfItemsArchived += $count } return $numberOfItemsArchived } function CompressFilesHelper { param ( [string[]] $sourceFilePaths, [string] $destinationPath, [string] $compressionLevel, [bool] $isUpdateMode, [double] $previousSegmentWeight, [double] $currentSegmentWeight ) $numberOfItemsArchived = ZipArchiveHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $null $previousSegmentWeight $currentSegmentWeight return $numberOfItemsArchived } function CompressSingleDirHelper { param ( [string] $sourceDirPath, [string] $destinationPath, [string] $compressionLevel, [bool] $useParentDirAsRoot, [bool] $isUpdateMode, [double] $previousSegmentWeight, [double] $currentSegmentWeight ) [System.Collections.Generic.List[System.String]]$subDirFiles = @() if ($useParentDirAsRoot) { $sourceDirInfo = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $sourceDirPath $sourceDirFullName = $sourceDirInfo.Parent.FullName # If the directory is present at the drive level the DirectoryInfo.Parent include '\' example: C:\ # On the other hand if the directory exists at a deper level then DirectoryInfo.Parent # has just the path (without an ending '\'). example C:\source if ($sourceDirFullName.Length -eq 3) { $modifiedSourceDirFullName = $sourceDirFullName } else { $modifiedSourceDirFullName = $sourceDirFullName + "\" } } else { $sourceDirFullName = $sourceDirPath $modifiedSourceDirFullName = $sourceDirFullName + "\" } $dirContents = Get-ChildItem -LiteralPath $sourceDirPath -Recurse foreach ($currentContent in $dirContents) { $isContainer = $currentContent -is [System.IO.DirectoryInfo] if (!$isContainer) { $subDirFiles.Add($currentContent.FullName) } else { # The currentContent points to a directory. # We need to check if the directory is an empty directory, if so such a # directory has to be explictly added to the archive file. # if there are no files in the directory the GetFiles() API returns an empty array. $files = $currentContent.GetFiles() if ($files.Count -eq 0) { $subDirFiles.Add($currentContent.FullName + "\") } } } $numberOfItemsArchived = ZipArchiveHelper $subDirFiles.ToArray() $destinationPath $compressionLevel $isUpdateMode $modifiedSourceDirFullName $previousSegmentWeight $currentSegmentWeight return $numberOfItemsArchived } function ZipArchiveHelper { param ( [System.Collections.Generic.List[System.String]] $sourcePaths, [string] $destinationPath, [string] $compressionLevel, [bool] $isUpdateMode, [string] $modifiedSourceDirFullName, [double] $previousSegmentWeight, [double] $currentSegmentWeight ) $numberOfItemsArchived = 0 $fileMode = [System.IO.FileMode]::Create $result = Test-Path -LiteralPath $DestinationPath -PathType Leaf if ($result -eq $true) { $fileMode = [System.IO.FileMode]::Open } Add-CompressionAssemblies try { # At this point we are sure that the archive file has write access. $archiveFileStreamArgs = @($destinationPath, $fileMode) $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Update, $false) $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs $currentEntryCount = 0 $progressBarStatus = ($LocalizedData.CompressProgressBarText -f $destinationPath) $bufferSize = 4kb $buffer = New-Object Byte[] $bufferSize foreach ($currentFilePath in $sourcePaths) { if ($modifiedSourceDirFullName -ne $null -and $modifiedSourceDirFullName.Length -gt 0) { $index = $currentFilePath.IndexOf($modifiedSourceDirFullName, [System.StringComparison]::OrdinalIgnoreCase) $currentFilePathSubString = $currentFilePath.Substring($index, $modifiedSourceDirFullName.Length) $relativeFilePath = $currentFilePath.Replace($currentFilePathSubString, "").Trim() } else { $relativeFilePath = [System.IO.Path]::GetFileName($currentFilePath) } # Update mode is selected. # Check to see if archive file already contains one or more zip files in it. if ($isUpdateMode -eq $true -and $zipArchive.Entries.Count -gt 0) { $entryToBeUpdated = $null # Check if the file already exists in the archive file. # If so replace it with new file from the input source. # If the file does not exist in the archive file then default to # create mode and create the entry in the archive file. foreach ($currentArchiveEntry in $zipArchive.Entries) { if ($currentArchiveEntry.FullName -eq $relativeFilePath) { $entryToBeUpdated = $currentArchiveEntry break } } if ($entryToBeUpdated -ne $null) { $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath) $entryToBeUpdated.Delete() } } $compression = CompressionLevelMapper $compressionLevel # If a directory needs to be added to an archive file, # by convention the .Net API's expect the path of the diretcory # to end with '\' to detect the path as an directory. if (!$relativeFilePath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) { try { try { $currentFileStream = [System.IO.File]::Open($currentFilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) } catch { # Failed to access the file. Write a non terminating error to the pipeline # and move on with the remaining files. $exception = $_.Exception if ($null -ne $_.Exception -and $null -ne $_.Exception.InnerException) { $exception = $_.Exception.InnerException } $errorRecord = CreateErrorRecordHelper "CompressArchiveUnauthorizedAccessError" $null ([System.Management.Automation.ErrorCategory]::PermissionDenied) $exception $currentFilePath Write-Error -ErrorRecord $errorRecord } if ($null -ne $currentFileStream) { $srcStream = New-Object System.IO.BinaryReader $currentFileStream $currentArchiveEntry = $zipArchive.CreateEntry($relativeFilePath, $compression) # Updating the File Creation time so that the same timestamp would be retained after expanding the compressed file. # At this point we are sure that Get-ChildItem would succeed. $currentArchiveEntry.LastWriteTime = (Get-Item -LiteralPath $currentFilePath).LastWriteTime $destStream = New-Object System.IO.BinaryWriter $currentArchiveEntry.Open() while ($numberOfBytesRead = $srcStream.Read($buffer, 0, $bufferSize)) { $destStream.Write($buffer, 0, $numberOfBytesRead) $destStream.Flush() } $numberOfItemsArchived += 1 $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath) } } finally { If ($null -ne $currentFileStream) { $currentFileStream.Dispose() } If ($null -ne $srcStream) { $srcStream.Dispose() } If ($null -ne $destStream) { $destStream.Dispose() } } } else { $currentArchiveEntry = $zipArchive.CreateEntry("$relativeFilePath", $compression) $numberOfItemsArchived += 1 $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath) } if ($null -ne $addItemtoArchiveFileMessage) { Write-Verbose $addItemtoArchiveFileMessage } $currentEntryCount += 1 ProgressBarHelper "Compress-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $sourcePaths.Count $currentEntryCount } } finally { If ($null -ne $zipArchive) { $zipArchive.Dispose() } If ($null -ne $archiveFileStream) { $archiveFileStream.Dispose() } # Complete writing progress. Write-Progress -Activity "Compress-Archive" -Completed } return $numberOfItemsArchived } <############################################################################################ # ValidateArchivePathHelper: This is a helper function used to validate the archive file # path & its file format. The only supported archive file format is .zip ############################################################################################> function ValidateArchivePathHelper { param ( [string] $archiveFile ) if ([System.IO.File]::Exists($archiveFile)) { $extension = [system.IO.Path]::GetExtension($archiveFile) # Invalid file extension is specifed for the zip file. if ($extension -ne $zipFileExtension) { $errorMessage = ($LocalizedData.InvalidZipFileExtensionError -f $extension, $zipFileExtension) ThrowTerminatingErrorHelper "NotSupportedArchiveFileExtension" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $extension } } else { $errorMessage = ($LocalizedData.PathNotFoundError -f $archiveFile) ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $archiveFile } } <############################################################################################ # ExpandArchiveHelper: This is a helper function used to expand the archive file contents # to the specified directory. ############################################################################################> function ExpandArchiveHelper { param ( [string] $archiveFile, [string] $expandedDir, [ref] $expandedItems, [boolean] $force, [boolean] $isVerbose, [boolean] $isConfirm ) Add-CompressionAssemblies try { # The existance of archive file has already been validated by ValidateArchivePathHelper # before calling this helper function. $archiveFileStreamArgs = @($archiveFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Read, $false) $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs if ($zipArchive.Entries.Count -eq 0) { $archiveFileIsEmpty = ($LocalizedData.ArchiveFileIsEmpty -f $archiveFile) Write-Verbose $archiveFileIsEmpty return } $currentEntryCount = 0 $progressBarStatus = ($LocalizedData.ExpandProgressBarText -f $archiveFile) # The archive entries can either be empty directories or files. foreach ($currentArchiveEntry in $zipArchive.Entries) { $currentArchiveEntryPath = Join-Path -Path $expandedDir -ChildPath $currentArchiveEntry.FullName $extension = [system.IO.Path]::GetExtension($currentArchiveEntryPath) # The current archive entry is an empty directory # The FullName of the Archive Entry representing a directory would end with a trailing '\'. if ($extension -eq [string]::Empty -and $currentArchiveEntryPath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) { $pathExists = Test-Path -LiteralPath $currentArchiveEntryPath # The current archive entry expects an empty directory. # Check if the existing directory is empty. If its not empty # then it means that user has added this directory by other means. if ($pathExists -eq $false) { New-Item $currentArchiveEntryPath -ItemType Directory -Confirm:$isConfirm | Out-Null if (Test-Path -LiteralPath $currentArchiveEntryPath -PathType Container) { $addEmptyDirectorytoExpandedPathMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentArchiveEntryPath) Write-Verbose $addEmptyDirectorytoExpandedPathMessage $expandedItems.Value += $currentArchiveEntryPath } } } else { try { $currentArchiveEntryFileInfo = New-Object -TypeName System.IO.FileInfo -ArgumentList $currentArchiveEntryPath $parentDirExists = Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container # If the Parent directory of the current entry in the archive file does not exist, then create it. if ($parentDirExists -eq $false) { New-Item $currentArchiveEntryFileInfo.DirectoryName -ItemType Directory -Confirm:$isConfirm | Out-Null if (!(Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container)) { # The directory referred by $currentArchiveEntryFileInfo.DirectoryName was not successfully created. # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked # and authorization was not provided when confirmation was prompted. In such a scenario, # we skip the current file in the archive and continue with the remaining archive file contents. Continue } $expandedItems.Value += $currentArchiveEntryFileInfo.DirectoryName } $hasNonTerminatingError = $false # Check if the file in to which the current archive entry contents # would be expanded already exists. if ($currentArchiveEntryFileInfo.Exists) { if ($force) { Remove-Item -LiteralPath $currentArchiveEntryFileInfo.FullName -Force -ErrorVariable ev -Verbose:$isVerbose -Confirm:$isConfirm if ($ev -ne $null) { $hasNonTerminatingError = $true } if (Test-Path -LiteralPath $currentArchiveEntryFileInfo.FullName -PathType Leaf) { # The file referred by $currentArchiveEntryFileInfo.FullName was not successfully removed. # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked # and authorization was not provided when confirmation was prompted. In such a scenario, # we skip the current file in the archive and continue with the remaining archive file contents. Continue } } else { # Write non-terminating error to the pipeline. $errorMessage = ($LocalizedData.FileExistsError -f $currentArchiveEntryFileInfo.FullName, $archiveFile, $currentArchiveEntryFileInfo.FullName, $currentArchiveEntryFileInfo.FullName) $errorRecord = CreateErrorRecordHelper "ExpandArchiveFileExists" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidOperation) $null $currentArchiveEntryFileInfo.FullName Write-Error -ErrorRecord $errorRecord $hasNonTerminatingError = $true } } if (!$hasNonTerminatingError) { [System.IO.Compression.ZipFileExtensions]::ExtractToFile($currentArchiveEntry, $currentArchiveEntryPath, $false) # Add the expanded file path to the $expandedItems array, # to keep track of all the expanded files created while expanding the archive file. # If user enters CTRL + C then at that point of time, all these expanded files # would be deleted as part of the clean up process. $expandedItems.Value += $currentArchiveEntryPath $addFiletoExpandedPathMessage = ($LocalizedData.CreateFileAtExpandedPath -f $currentArchiveEntryPath) Write-Verbose $addFiletoExpandedPathMessage } } finally { If ($null -ne $destStream) { $destStream.Dispose() } If ($null -ne $srcStream) { $srcStream.Dispose() } } } $currentEntryCount += 1 # $currentSegmentWeight is Set to 100 giving equal weightage to each file that is getting expanded. # $previousSegmentWeight is set to 0 as there are no prior segments. $previousSegmentWeight = 0 $currentSegmentWeight = 100 ProgressBarHelper "Expand-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $zipArchive.Entries.Count $currentEntryCount } } finally { If ($null -ne $zipArchive) { $zipArchive.Dispose() } If ($null -ne $archiveFileStream) { $archiveFileStream.Dispose() } # Complete writing progress. Write-Progress -Activity "Expand-Archive" -Completed } } <############################################################################################ # ProgressBarHelper: This is a helper function used to display progress message. # This function is used by both Compress-Archive & Expand-Archive to display archive file # creation/expansion progress. ############################################################################################> function ProgressBarHelper { param ( [string] $cmdletName, [string] $status, [double] $previousSegmentWeight, [double] $currentSegmentWeight, [int] $totalNumberofEntries, [int] $currentEntryCount ) if ($currentEntryCount -gt 0 -and $totalNumberofEntries -gt 0 -and $previousSegmentWeight -ge 0 -and $currentSegmentWeight -gt 0) { $entryDefaultWeight = $currentSegmentWeight / [double]$totalNumberofEntries $percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount) Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete } } <############################################################################################ # CSVHelper: This is a helper function used to append comma after each path specifid by # the SourcePath array. This helper function is used to display all the user supplied paths # in the WhatIf message. ############################################################################################> function CSVHelper { param ( [string[]] $sourcePath ) # SourcePath has already been validated by the calling funcation. if ($sourcePath.Count -gt 1) { $sourcePathInCsvFormat = "`n" for ($currentIndex = 0; $currentIndex -lt $sourcePath.Count; $currentIndex++) { if ($currentIndex -eq $sourcePath.Count - 1) { $sourcePathInCsvFormat += $sourcePath[$currentIndex] } else { $sourcePathInCsvFormat += $sourcePath[$currentIndex] + "`n" } } } else { $sourcePathInCsvFormat = $sourcePath } return $sourcePathInCsvFormat } <############################################################################################ # ThrowTerminatingErrorHelper: This is a helper function used to throw terminating error. ############################################################################################> function ThrowTerminatingErrorHelper { param ( [string] $errorId, [string] $errorMessage, [System.Management.Automation.ErrorCategory] $errorCategory, [object] $targetObject, [Exception] $innerException ) if ($innerException -eq $null) { $exception = New-object System.IO.IOException $errorMessage } else { $exception = New-Object System.IO.IOException $errorMessage, $innerException } $exception = New-Object System.IO.IOException $errorMessage $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject $PSCmdlet.ThrowTerminatingError($errorRecord) } <############################################################################################ # CreateErrorRecordHelper: This is a helper function used to create an ErrorRecord ############################################################################################> function CreateErrorRecordHelper { param ( [string] $errorId, [string] $errorMessage, [System.Management.Automation.ErrorCategory] $errorCategory, [Exception] $exception, [object] $targetObject ) if ($null -eq $exception) { $exception = New-Object System.IO.IOException $errorMessage } $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject return $errorRecord } #endregion Utility Functions $inputPaths = @() $destinationParentDir = [system.IO.Path]::GetDirectoryName($DestinationPath) if ($null -eq $destinationParentDir) { $errorMessage = ($LocalizedData.InvalidDestinationPath -f $DestinationPath) ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath } if ($destinationParentDir -eq [string]::Empty) { $destinationParentDir = '.' } $achiveFileName = [system.IO.Path]::GetFileName($DestinationPath) $destinationParentDir = GetResolvedPathHelper $destinationParentDir $false $PSCmdlet if ($destinationParentDir.Count -gt 1) { $errorMessage = ($LocalizedData.InvalidArchiveFilePathError -f $DestinationPath, "DestinationPath", "DestinationPath") ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath } IsValidFileSystemPath $destinationParentDir | Out-Null $DestinationPath = Join-Path -Path $destinationParentDir -ChildPath $achiveFileName # GetExtension API does not validate for the actual existance of the path. $extension = [system.IO.Path]::GetExtension($DestinationPath) # If user does not specify .Zip extension, we append it. If ($extension -eq [string]::Empty) { $DestinationPathWithOutExtension = $DestinationPath $DestinationPath = $DestinationPathWithOutExtension + $zipFileExtension $appendArchiveFileExtensionMessage = ($LocalizedData.AppendArchiveFileExtensionMessage -f $DestinationPathWithOutExtension, $DestinationPath) Write-Verbose $appendArchiveFileExtensionMessage } else { # Invalid file extension is specified for the zip file to be created. if ($extension -ne $zipFileExtension) { $errorMessage = ($LocalizedData.InvalidZipFileExtensionError -f $extension, $zipFileExtension) ThrowTerminatingErrorHelper "NotSupportedArchiveFileExtension" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $extension } } $archiveFileExist = Test-Path -LiteralPath $DestinationPath -PathType Leaf if ($archiveFileExist -and ($Update -eq $false -and $Force -eq $false)) { $errorMessage = ($LocalizedData.ZipFileExistError -f $DestinationPath) ThrowTerminatingErrorHelper "ArchiveFileExists" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath } # If archive file already exists and if -Update is specified, then we check to see # if we have write access permission to update the existing archive file. if ($archiveFileExist -and $Update -eq $true) { $item = Get-Item -Path $DestinationPath if ($item.Attributes.ToString().Contains("ReadOnly")) { $errorMessage = ($LocalizedData.ArchiveFileIsReadOnly -f $DestinationPath) ThrowTerminatingErrorHelper "ArchiveFileIsReadOnly" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidOperation) $DestinationPath } } $isWhatIf = $psboundparameters.ContainsKey("WhatIf") if (!$isWhatIf) { $preparingToCompressVerboseMessage = ($LocalizedData.PreparingToCompressVerboseMessage) Write-Verbose $preparingToCompressVerboseMessage $progressBarStatus = ($LocalizedData.CompressProgressBarText -f $DestinationPath) ProgressBarHelper "Compress-Archive" $progressBarStatus 0 100 100 1 } } PROCESS { if ($PsCmdlet.ParameterSetName -eq "Path" -or $PsCmdlet.ParameterSetName -eq "PathWithForce" -or $PsCmdlet.ParameterSetName -eq "PathWithUpdate") { $inputPaths += $Path } if ($PsCmdlet.ParameterSetName -eq "LiteralPath" -or $PsCmdlet.ParameterSetName -eq "LiteralPathWithForce" -or $PsCmdlet.ParameterSetName -eq "LiteralPathWithUpdate") { $inputPaths += $LiteralPath } } END { # If archive file already exists and if -Force is specified, we delete the # existing artchive file and create a brand new one. if (($PsCmdlet.ParameterSetName -eq "PathWithForce" -or $PsCmdlet.ParameterSetName -eq "LiteralPathWithForce") -and $archiveFileExist) { Remove-Item -Path $DestinationPath -Force -ErrorAction Stop } # Validate Source Path depeding on parameter set being used. # The specified source path conatins one or more files or directories that needs # to be compressed. $isLiteralPathUsed = $false if ($PsCmdlet.ParameterSetName -eq "LiteralPath" -or $PsCmdlet.ParameterSetName -eq "LiteralPathWithForce" -or $PsCmdlet.ParameterSetName -eq "LiteralPathWithUpdate") { $isLiteralPathUsed = $true } ValidateDuplicateFileSystemPath $PsCmdlet.ParameterSetName $inputPaths $resolvedPaths = GetResolvedPathHelper $inputPaths $isLiteralPathUsed $PSCmdlet IsValidFileSystemPath $resolvedPaths | Out-Null $sourcePath = $resolvedPaths; # CSVHelper: This is a helper function used to append comma after each path specifid by # the $sourcePath array. The comma saperated paths are displayed in the -WhatIf message. $sourcePathInCsvFormat = CSVHelper $sourcePath if ($pscmdlet.ShouldProcess($sourcePathInCsvFormat)) { try { # StopProcessing is not avaliable in Script cmdlets. However the pipleline execution # is terminated when ever 'CTRL + C' is entered by user to terminate the cmdlet execution. # The finally block is executed whenever pipleline is terminated. # $isArchiveFileProcessingComplete variable is used to track if 'CTRL + C' is entered by the # user. $isArchiveFileProcessingComplete = $false $numberOfItemsArchived = CompressArchiveHelper $sourcePath $DestinationPath $CompressionLevel $Update $isArchiveFileProcessingComplete = $true } finally { # The $isArchiveFileProcessingComplete would be set to $false if user has typed 'CTRL + C' to # terminate the cmdlet execution or if an unhandled exception is thrown. # $numberOfItemsArchived contains the count of number of files or directories add to the archive file. # If the newly created archive file is empty then we delete it as its not usable. if (($isArchiveFileProcessingComplete -eq $false) -or ($numberOfItemsArchived -eq 0)) { $DeleteArchiveFileMessage = ($LocalizedData.DeleteArchiveFile -f $DestinationPath) Write-Verbose $DeleteArchiveFileMessage # delete the partial archive file created. if (Test-Path $DestinationPath) { Remove-Item -LiteralPath $DestinationPath -Force -Recurse -ErrorAction SilentlyContinue } } } } } } } if ($PSVersionTable.PSVersion.Major -lt 5) { <# Copied from the Microsoft Module: Microsoft.PowerShell.Archive Which ships with PowerShell Version 5 but will run under v3. #> function Expand-Archive { <# .SYNOPSIS Extracts files from a specified archive (zipped) file. .DESCRIPTION The Expand-Archive cmdlet extracts files from a specified zipped archive file to a specified destination folder. An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage. .PARAMETER Path Specifies the path to the archive file. .PARAMETER LiteralPath Specifies the path to an archive file. Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. Wildcard characters are not supported. If the path includes escape characters, enclose each escape character in single quotation marks, to instruct Windows PowerShell not to interpret any characters as escape sequences. .PARAMETER DestinationPath Specifies the path to the folder in which you want the command to save extracted files. Enter the path to a folder, but do not specify a file name or file name extension. This parameter is required. .PARAMETER Force Forces the command to run without asking for user confirmation. .PARAMETER Confirm Prompts you for confirmation before running the cmdlet. .PARAMETER WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. .EXAMPLE Example 1: Extract the contents of an archive PS C:\>Expand-Archive -LiteralPath C:\Archives\Draft.Zip -DestinationPath C:\Reference This command extracts the contents of an existing archive file, Draft.zip, into the folder specified by the DestinationPath parameter, C:\Reference. .EXAMPLE Example 2: Extract the contents of an archive in the current folder PS C:\>Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference This command extracts the contents of an existing archive file in the current folder, Draft.zip, into the folder specified by the DestinationPath parameter, C:\Reference. #> [CmdletBinding( DefaultParameterSetName = "Path", SupportsShouldProcess, HelpUri = "http://go.microsoft.com/fwlink/?LinkID=393253")] param ( [parameter ( Mandatory, Position = 0, ParameterSetName = "Path", ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [string] $Path, [parameter ( Mandatory, ParameterSetName = "LiteralPath", ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [Alias("PSPath")] [string] $LiteralPath, [parameter ( Position = 1, ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [ValidateNotNullOrEmpty()] [string] $DestinationPath, [parameter ( ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $false)] [switch] $Force ) BEGIN { Add-Type -AssemblyName System.IO.Compression -ErrorAction Ignore Add-Type -AssemblyName System.IO.Compression.FileSystem -ErrorAction Ignore $zipFileExtension = ".zip" $LocalizedData = ConvertFrom-StringData @' PathNotFoundError=The path '{0}' either does not exist or is not a valid file system path. ExpandArchiveInValidDestinationPath=The path '{0}' is not a valid file system directory path. InvalidZipFileExtensionError={0} is not a supported archive file format. {1} is the only supported archive file format. ArchiveFileIsReadOnly=The attributes of the archive file {0} is set to 'ReadOnly' hence it cannot be updated. If you intend to update the existing archive file, remove the 'ReadOnly' attribute on the archive file else use -Force parameter to override and create a new archive file. ZipFileExistError=The archive file {0} already exists. Use the -Update parameter to update the existing archive file or use the -Force parameter to overwrite the existing archive file. DuplicatePathFoundError=The input to {0} parameter contains a duplicate path '{1}'. Provide a unique set of paths as input to {2} parameter. ArchiveFileIsEmpty=The archive file {0} is empty. CompressProgressBarText=The archive file '{0}' creation is in progress... ExpandProgressBarText=The archive file '{0}' expansion is in progress... AppendArchiveFileExtensionMessage=The archive file path '{0}' supplied to the DestinationPath patameter does not include .zip extension. Hence .zip is appended to the supplied DestinationPath path and the archive file would be created at '{1}'. AddItemtoArchiveFile=Adding '{0}'. CreateFileAtExpandedPath=Created '{0}'. InvalidArchiveFilePathError=The archive file path '{0}' specified as input to the {1} parameter is resolving to multiple file system paths. Provide a unique path to the {2} parameter where the archive file has to be created. InvalidExpandedDirPathError=The directory path '{0}' specified as input to the DestinationPath parameter is resolving to multiple file system paths. Provide a unique path to the Destination parameter where the archive file contents have to be expanded. FileExistsError=Failed to create file '{0}' while expanding the archive file '{1}' contents as the file '{2}' already exists. Use the -Force parameter if you want to overwrite the existing directory '{3}' contents when expanding the archive file. DeleteArchiveFile=The partially created archive file '{0}' is deleted as it is not usable. InvalidDestinationPath=The destination path '{0}' does not contain a valid archive file name. PreparingToCompressVerboseMessage=Preparing to compress... PreparingToExpandVerboseMessage=Preparing to expand... '@ #region Utility Functions function GetResolvedPathHelper { param ( [string[]] $path, [boolean] $isLiteralPath, [System.Management.Automation.PSCmdlet] $callerPSCmdlet ) $resolvedPaths = @() # null and empty check are are already done on Path parameter at the cmdlet layer. foreach ($currentPath in $path) { try { if ($isLiteralPath) { $currentResolvedPaths = Resolve-Path -LiteralPath $currentPath -ErrorAction Stop } else { $currentResolvedPaths = Resolve-Path -Path $currentPath -ErrorAction Stop } } catch { $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath) $exception = New-Object System.InvalidOperationException $errorMessage, $_.Exception $errorRecord = CreateErrorRecordHelper "ArchiveCmdletPathNotFound" $null ([System.Management.Automation.ErrorCategory]::InvalidArgument) $exception $currentPath $callerPSCmdlet.ThrowTerminatingError($errorRecord) } foreach ($currentResolvedPath in $currentResolvedPaths) { $resolvedPaths += $currentResolvedPath.ProviderPath } } $resolvedPaths } function Add-CompressionAssemblies { if ($PSEdition -eq "Desktop") { Add-Type -AssemblyName System.IO.Compression Add-Type -AssemblyName System.IO.Compression.FileSystem } } function IsValidFileSystemPath { param ( [string[]] $path ) $result = $true; # null and empty check are are already done on Path parameter at the cmdlet layer. foreach ($currentPath in $path) { if (!([System.IO.File]::Exists($currentPath) -or [System.IO.Directory]::Exists($currentPath))) { $errorMessage = ($LocalizedData.PathNotFoundError -f $currentPath) ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath } } return $result; } function ValidateDuplicateFileSystemPath { param ( [string] $inputParameter, [string[]] $path ) $uniqueInputPaths = @() # null and empty check are are already done on Path parameter at the cmdlet layer. foreach ($currentPath in $path) { $currentInputPath = $currentPath.ToUpper() if ($uniqueInputPaths.Contains($currentInputPath)) { $errorMessage = ($LocalizedData.DuplicatePathFoundError -f $inputParameter, $currentPath, $inputParameter) ThrowTerminatingErrorHelper "DuplicatePathFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $currentPath } else { $uniqueInputPaths += $currentInputPath } } } function CompressionLevelMapper { param ( [string] $compressionLevel ) $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Optimal # CompressionLevel format is already validated at the cmdlet layer. switch ($compressionLevel.ToString()) { "Fastest" { $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::Fastest } "NoCompression" { $compressionLevelFormat = [System.IO.Compression.CompressionLevel]::NoCompression } } return $compressionLevelFormat } function CompressArchiveHelper { param ( [string[]] $sourcePath, [string] $destinationPath, [string] $compressionLevel, [bool] $isUpdateMode ) $numberOfItemsArchived = 0 $sourceFilePaths = @() $sourceDirPaths = @() foreach ($currentPath in $sourcePath) { $result = Test-Path -LiteralPath $currentPath -PathType Leaf if ($result -eq $true) { $sourceFilePaths += $currentPath } else { $sourceDirPaths += $currentPath } } # The Soure Path contains one or more directory (this directory can have files under it) and no files to be compressed. if ($sourceFilePaths.Count -eq 0 -and $sourceDirPaths.Count -gt 0) { $currentSegmentWeight = 100 / [double]$sourceDirPaths.Count $previousSegmentWeight = 0 foreach ($currentSourceDirPath in $sourceDirPaths) { $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight $numberOfItemsArchived += $count $previousSegmentWeight += $currentSegmentWeight } } # The Soure Path contains only files to be compressed. elseIf ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -eq 0) { # $previousSegmentWeight is equal to 0 as there are no prior segments. # $currentSegmentWeight is set to 100 as all files have equal weightage. $previousSegmentWeight = 0 $currentSegmentWeight = 100 $numberOfItemsArchived = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight } # The Soure Path contains one or more files and one or more directories (this directory can have files under it) to be compressed. elseif ($sourceFilePaths.Count -gt 0 -and $sourceDirPaths.Count -gt 0) { # each directory is considered as an individual segments & all the individual files are clubed in to a separate sgemnet. $currentSegmentWeight = 100 / [double]($sourceDirPaths.Count + 1) $previousSegmentWeight = 0 foreach ($currentSourceDirPath in $sourceDirPaths) { $count = CompressSingleDirHelper $currentSourceDirPath $destinationPath $compressionLevel $true $isUpdateMode $previousSegmentWeight $currentSegmentWeight $numberOfItemsArchived += $count $previousSegmentWeight += $currentSegmentWeight } $count = CompressFilesHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $previousSegmentWeight $currentSegmentWeight $numberOfItemsArchived += $count } return $numberOfItemsArchived } function CompressFilesHelper { param ( [string[]] $sourceFilePaths, [string] $destinationPath, [string] $compressionLevel, [bool] $isUpdateMode, [double] $previousSegmentWeight, [double] $currentSegmentWeight ) $numberOfItemsArchived = ZipArchiveHelper $sourceFilePaths $destinationPath $compressionLevel $isUpdateMode $null $previousSegmentWeight $currentSegmentWeight return $numberOfItemsArchived } function CompressSingleDirHelper { param ( [string] $sourceDirPath, [string] $destinationPath, [string] $compressionLevel, [bool] $useParentDirAsRoot, [bool] $isUpdateMode, [double] $previousSegmentWeight, [double] $currentSegmentWeight ) [System.Collections.Generic.List[System.String]]$subDirFiles = @() if ($useParentDirAsRoot) { $sourceDirInfo = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList $sourceDirPath $sourceDirFullName = $sourceDirInfo.Parent.FullName # If the directory is present at the drive level the DirectoryInfo.Parent include '\' example: C:\ # On the other hand if the directory exists at a deper level then DirectoryInfo.Parent # has just the path (without an ending '\'). example C:\source if ($sourceDirFullName.Length -eq 3) { $modifiedSourceDirFullName = $sourceDirFullName } else { $modifiedSourceDirFullName = $sourceDirFullName + "\" } } else { $sourceDirFullName = $sourceDirPath $modifiedSourceDirFullName = $sourceDirFullName + "\" } $dirContents = Get-ChildItem -LiteralPath $sourceDirPath -Recurse foreach ($currentContent in $dirContents) { $isContainer = $currentContent -is [System.IO.DirectoryInfo] if (!$isContainer) { $subDirFiles.Add($currentContent.FullName) } else { # The currentContent points to a directory. # We need to check if the directory is an empty directory, if so such a # directory has to be explictly added to the archive file. # if there are no files in the directory the GetFiles() API returns an empty array. $files = $currentContent.GetFiles() if ($files.Count -eq 0) { $subDirFiles.Add($currentContent.FullName + "\") } } } $numberOfItemsArchived = ZipArchiveHelper $subDirFiles.ToArray() $destinationPath $compressionLevel $isUpdateMode $modifiedSourceDirFullName $previousSegmentWeight $currentSegmentWeight return $numberOfItemsArchived } function ZipArchiveHelper { param ( [System.Collections.Generic.List[System.String]] $sourcePaths, [string] $destinationPath, [string] $compressionLevel, [bool] $isUpdateMode, [string] $modifiedSourceDirFullName, [double] $previousSegmentWeight, [double] $currentSegmentWeight ) $numberOfItemsArchived = 0 $fileMode = [System.IO.FileMode]::Create $result = Test-Path -LiteralPath $DestinationPath -PathType Leaf if ($result -eq $true) { $fileMode = [System.IO.FileMode]::Open } Add-CompressionAssemblies try { # At this point we are sure that the archive file has write access. $archiveFileStreamArgs = @($destinationPath, $fileMode) $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Update, $false) $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs $currentEntryCount = 0 $progressBarStatus = ($LocalizedData.CompressProgressBarText -f $destinationPath) $bufferSize = 4kb $buffer = New-Object Byte[] $bufferSize foreach ($currentFilePath in $sourcePaths) { if ($modifiedSourceDirFullName -ne $null -and $modifiedSourceDirFullName.Length -gt 0) { $index = $currentFilePath.IndexOf($modifiedSourceDirFullName, [System.StringComparison]::OrdinalIgnoreCase) $currentFilePathSubString = $currentFilePath.Substring($index, $modifiedSourceDirFullName.Length) $relativeFilePath = $currentFilePath.Replace($currentFilePathSubString, "").Trim() } else { $relativeFilePath = [System.IO.Path]::GetFileName($currentFilePath) } # Update mode is selected. # Check to see if archive file already contains one or more zip files in it. if ($isUpdateMode -eq $true -and $zipArchive.Entries.Count -gt 0) { $entryToBeUpdated = $null # Check if the file already exists in the archive file. # If so replace it with new file from the input source. # If the file does not exist in the archive file then default to # create mode and create the entry in the archive file. foreach ($currentArchiveEntry in $zipArchive.Entries) { if ($currentArchiveEntry.FullName -eq $relativeFilePath) { $entryToBeUpdated = $currentArchiveEntry break } } if ($entryToBeUpdated -ne $null) { $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath) $entryToBeUpdated.Delete() } } $compression = CompressionLevelMapper $compressionLevel # If a directory needs to be added to an archive file, # by convention the .Net API's expect the path of the diretcory # to end with '\' to detect the path as an directory. if (!$relativeFilePath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) { try { try { $currentFileStream = [System.IO.File]::Open($currentFilePath, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) } catch { # Failed to access the file. Write a non terminating error to the pipeline # and move on with the remaining files. $exception = $_.Exception if ($null -ne $_.Exception -and $null -ne $_.Exception.InnerException) { $exception = $_.Exception.InnerException } $errorRecord = CreateErrorRecordHelper "CompressArchiveUnauthorizedAccessError" $null ([System.Management.Automation.ErrorCategory]::PermissionDenied) $exception $currentFilePath Write-Error -ErrorRecord $errorRecord } if ($null -ne $currentFileStream) { $srcStream = New-Object System.IO.BinaryReader $currentFileStream $currentArchiveEntry = $zipArchive.CreateEntry($relativeFilePath, $compression) # Updating the File Creation time so that the same timestamp would be retained after expanding the compressed file. # At this point we are sure that Get-ChildItem would succeed. $currentArchiveEntry.LastWriteTime = (Get-Item -LiteralPath $currentFilePath).LastWriteTime $destStream = New-Object System.IO.BinaryWriter $currentArchiveEntry.Open() while ($numberOfBytesRead = $srcStream.Read($buffer, 0, $bufferSize)) { $destStream.Write($buffer, 0, $numberOfBytesRead) $destStream.Flush() } $numberOfItemsArchived += 1 $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath) } } finally { If ($null -ne $currentFileStream) { $currentFileStream.Dispose() } If ($null -ne $srcStream) { $srcStream.Dispose() } If ($null -ne $destStream) { $destStream.Dispose() } } } else { $currentArchiveEntry = $zipArchive.CreateEntry("$relativeFilePath", $compression) $numberOfItemsArchived += 1 $addItemtoArchiveFileMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentFilePath) } if ($null -ne $addItemtoArchiveFileMessage) { Write-Verbose $addItemtoArchiveFileMessage } $currentEntryCount += 1 ProgressBarHelper "Compress-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $sourcePaths.Count $currentEntryCount } } finally { If ($null -ne $zipArchive) { $zipArchive.Dispose() } If ($null -ne $archiveFileStream) { $archiveFileStream.Dispose() } # Complete writing progress. Write-Progress -Activity "Compress-Archive" -Completed } return $numberOfItemsArchived } <############################################################################################ # ValidateArchivePathHelper: This is a helper function used to validate the archive file # path & its file format. The only supported archive file format is .zip ############################################################################################> function ValidateArchivePathHelper { param ( [string] $archiveFile ) if ([System.IO.File]::Exists($archiveFile)) { $extension = [system.IO.Path]::GetExtension($archiveFile) # Invalid file extension is specifed for the zip file. if ($extension -ne $zipFileExtension) { $errorMessage = ($LocalizedData.InvalidZipFileExtensionError -f $extension, $zipFileExtension) ThrowTerminatingErrorHelper "NotSupportedArchiveFileExtension" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $extension } } else { $errorMessage = ($LocalizedData.PathNotFoundError -f $archiveFile) ThrowTerminatingErrorHelper "PathNotFound" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $archiveFile } } <############################################################################################ # ExpandArchiveHelper: This is a helper function used to expand the archive file contents # to the specified directory. ############################################################################################> function ExpandArchiveHelper { param ( [string] $archiveFile, [string] $expandedDir, [ref] $expandedItems, [boolean] $force, [boolean] $isVerbose, [boolean] $isConfirm ) Add-CompressionAssemblies try { # The existance of archive file has already been validated by ValidateArchivePathHelper # before calling this helper function. $archiveFileStreamArgs = @($archiveFile, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) $archiveFileStream = New-Object -TypeName System.IO.FileStream -ArgumentList $archiveFileStreamArgs $zipArchiveArgs = @($archiveFileStream, [System.IO.Compression.ZipArchiveMode]::Read, $false) $zipArchive = New-Object -TypeName System.IO.Compression.ZipArchive -ArgumentList $zipArchiveArgs if ($zipArchive.Entries.Count -eq 0) { $archiveFileIsEmpty = ($LocalizedData.ArchiveFileIsEmpty -f $archiveFile) Write-Verbose $archiveFileIsEmpty return } $currentEntryCount = 0 $progressBarStatus = ($LocalizedData.ExpandProgressBarText -f $archiveFile) # The archive entries can either be empty directories or files. foreach ($currentArchiveEntry in $zipArchive.Entries) { $currentArchiveEntryPath = Join-Path -Path $expandedDir -ChildPath $currentArchiveEntry.FullName $extension = [system.IO.Path]::GetExtension($currentArchiveEntryPath) # The current archive entry is an empty directory # The FullName of the Archive Entry representing a directory would end with a trailing '\'. if ($extension -eq [string]::Empty -and $currentArchiveEntryPath.EndsWith("\", [StringComparison]::OrdinalIgnoreCase)) { $pathExists = Test-Path -LiteralPath $currentArchiveEntryPath # The current archive entry expects an empty directory. # Check if the existing directory is empty. If its not empty # then it means that user has added this directory by other means. if ($pathExists -eq $false) { New-Item $currentArchiveEntryPath -ItemType Directory -Confirm:$isConfirm | Out-Null if (Test-Path -LiteralPath $currentArchiveEntryPath -PathType Container) { $addEmptyDirectorytoExpandedPathMessage = ($LocalizedData.AddItemtoArchiveFile -f $currentArchiveEntryPath) Write-Verbose $addEmptyDirectorytoExpandedPathMessage $expandedItems.Value += $currentArchiveEntryPath } } } else { try { $currentArchiveEntryFileInfo = New-Object -TypeName System.IO.FileInfo -ArgumentList $currentArchiveEntryPath $parentDirExists = Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container # If the Parent directory of the current entry in the archive file does not exist, then create it. if ($parentDirExists -eq $false) { New-Item $currentArchiveEntryFileInfo.DirectoryName -ItemType Directory -Confirm:$isConfirm | Out-Null if (!(Test-Path -LiteralPath $currentArchiveEntryFileInfo.DirectoryName -PathType Container)) { # The directory referred by $currentArchiveEntryFileInfo.DirectoryName was not successfully created. # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked # and authorization was not provided when confirmation was prompted. In such a scenario, # we skip the current file in the archive and continue with the remaining archive file contents. Continue } $expandedItems.Value += $currentArchiveEntryFileInfo.DirectoryName } $hasNonTerminatingError = $false # Check if the file in to which the current archive entry contents # would be expanded already exists. if ($currentArchiveEntryFileInfo.Exists) { if ($force) { Remove-Item -LiteralPath $currentArchiveEntryFileInfo.FullName -Force -ErrorVariable ev -Verbose:$isVerbose -Confirm:$isConfirm if ($ev -ne $null) { $hasNonTerminatingError = $true } if (Test-Path -LiteralPath $currentArchiveEntryFileInfo.FullName -PathType Leaf) { # The file referred by $currentArchiveEntryFileInfo.FullName was not successfully removed. # This could be because the user has specified -Confirm paramter when Expand-Archive was invoked # and authorization was not provided when confirmation was prompted. In such a scenario, # we skip the current file in the archive and continue with the remaining archive file contents. Continue } } else { # Write non-terminating error to the pipeline. $errorMessage = ($LocalizedData.FileExistsError -f $currentArchiveEntryFileInfo.FullName, $archiveFile, $currentArchiveEntryFileInfo.FullName, $currentArchiveEntryFileInfo.FullName) $errorRecord = CreateErrorRecordHelper "ExpandArchiveFileExists" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidOperation) $null $currentArchiveEntryFileInfo.FullName Write-Error -ErrorRecord $errorRecord $hasNonTerminatingError = $true } } if (!$hasNonTerminatingError) { [System.IO.Compression.ZipFileExtensions]::ExtractToFile($currentArchiveEntry, $currentArchiveEntryPath, $false) # Add the expanded file path to the $expandedItems array, # to keep track of all the expanded files created while expanding the archive file. # If user enters CTRL + C then at that point of time, all these expanded files # would be deleted as part of the clean up process. $expandedItems.Value += $currentArchiveEntryPath $addFiletoExpandedPathMessage = ($LocalizedData.CreateFileAtExpandedPath -f $currentArchiveEntryPath) Write-Verbose $addFiletoExpandedPathMessage } } finally { If ($null -ne $destStream) { $destStream.Dispose() } If ($null -ne $srcStream) { $srcStream.Dispose() } } } $currentEntryCount += 1 # $currentSegmentWeight is Set to 100 giving equal weightage to each file that is getting expanded. # $previousSegmentWeight is set to 0 as there are no prior segments. $previousSegmentWeight = 0 $currentSegmentWeight = 100 ProgressBarHelper "Expand-Archive" $progressBarStatus $previousSegmentWeight $currentSegmentWeight $zipArchive.Entries.Count $currentEntryCount } } finally { If ($null -ne $zipArchive) { $zipArchive.Dispose() } If ($null -ne $archiveFileStream) { $archiveFileStream.Dispose() } # Complete writing progress. Write-Progress -Activity "Expand-Archive" -Completed } } <############################################################################################ # ProgressBarHelper: This is a helper function used to display progress message. # This function is used by both Compress-Archive & Expand-Archive to display archive file # creation/expansion progress. ############################################################################################> function ProgressBarHelper { param ( [string] $cmdletName, [string] $status, [double] $previousSegmentWeight, [double] $currentSegmentWeight, [int] $totalNumberofEntries, [int] $currentEntryCount ) if ($currentEntryCount -gt 0 -and $totalNumberofEntries -gt 0 -and $previousSegmentWeight -ge 0 -and $currentSegmentWeight -gt 0) { $entryDefaultWeight = $currentSegmentWeight / [double]$totalNumberofEntries $percentComplete = $previousSegmentWeight + ($entryDefaultWeight * $currentEntryCount) Write-Progress -Activity $cmdletName -Status $status -PercentComplete $percentComplete } } <############################################################################################ # CSVHelper: This is a helper function used to append comma after each path specifid by # the SourcePath array. This helper function is used to display all the user supplied paths # in the WhatIf message. ############################################################################################> function CSVHelper { param ( [string[]] $sourcePath ) # SourcePath has already been validated by the calling funcation. if ($sourcePath.Count -gt 1) { $sourcePathInCsvFormat = "`n" for ($currentIndex = 0; $currentIndex -lt $sourcePath.Count; $currentIndex++) { if ($currentIndex -eq $sourcePath.Count - 1) { $sourcePathInCsvFormat += $sourcePath[$currentIndex] } else { $sourcePathInCsvFormat += $sourcePath[$currentIndex] + "`n" } } } else { $sourcePathInCsvFormat = $sourcePath } return $sourcePathInCsvFormat } <############################################################################################ # ThrowTerminatingErrorHelper: This is a helper function used to throw terminating error. ############################################################################################> function ThrowTerminatingErrorHelper { param ( [string] $errorId, [string] $errorMessage, [System.Management.Automation.ErrorCategory] $errorCategory, [object] $targetObject, [Exception] $innerException ) if ($innerException -eq $null) { $exception = New-object System.IO.IOException $errorMessage } else { $exception = New-Object System.IO.IOException $errorMessage, $innerException } $exception = New-Object System.IO.IOException $errorMessage $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject $PSCmdlet.ThrowTerminatingError($errorRecord) } <############################################################################################ # CreateErrorRecordHelper: This is a helper function used to create an ErrorRecord ############################################################################################> function CreateErrorRecordHelper { param ( [string] $errorId, [string] $errorMessage, [System.Management.Automation.ErrorCategory] $errorCategory, [Exception] $exception, [object] $targetObject ) if ($null -eq $exception) { $exception = New-Object System.IO.IOException $errorMessage } $errorRecord = New-Object System.Management.Automation.ErrorRecord $exception, $errorId, $errorCategory, $targetObject return $errorRecord } #endregion Utility Functions $isVerbose = $psboundparameters.ContainsKey("Verbose") $isConfirm = $psboundparameters.ContainsKey("Confirm") $isDestinationPathProvided = $true if ($DestinationPath -eq [string]::Empty) { $resolvedDestinationPath = $pwd $isDestinationPathProvided = $false } else { $destinationPathExists = Test-Path -Path $DestinationPath -PathType Container if ($destinationPathExists) { $resolvedDestinationPath = GetResolvedPathHelper $DestinationPath $false $PSCmdlet if ($resolvedDestinationPath.Count -gt 1) { $errorMessage = ($LocalizedData.InvalidExpandedDirPathError -f $DestinationPath) ThrowTerminatingErrorHelper "InvalidDestinationPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath } # At this point we are sure that the provided path resolves to a valid single path. # Calling Resolve-Path again to get the underlying provider name. $suppliedDestinationPath = Resolve-Path -Path $DestinationPath if ($suppliedDestinationPath.Provider.Name -ne "FileSystem") { $errorMessage = ($LocalizedData.ExpandArchiveInValidDestinationPath -f $DestinationPath) ThrowTerminatingErrorHelper "InvalidDirectoryPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath } } else { $createdItem = New-Item -Path $DestinationPath -ItemType Directory -Confirm:$isConfirm -Verbose:$isVerbose -ErrorAction Stop if ($createdItem -ne $null -and $createdItem.PSProvider.Name -ne "FileSystem") { Remove-Item "$DestinationPath" -Force -Recurse -ErrorAction SilentlyContinue $errorMessage = ($LocalizedData.ExpandArchiveInValidDestinationPath -f $DestinationPath) ThrowTerminatingErrorHelper "InvalidDirectoryPath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $DestinationPath } $resolvedDestinationPath = GetResolvedPathHelper $DestinationPath $true $PSCmdlet } } $isWhatIf = $psboundparameters.ContainsKey("WhatIf") if (!$isWhatIf) { $preparingToExpandVerboseMessage = ($LocalizedData.PreparingToExpandVerboseMessage) Write-Verbose $preparingToExpandVerboseMessage $progressBarStatus = ($LocalizedData.ExpandProgressBarText -f $DestinationPath) ProgressBarHelper "Expand-Archive" $progressBarStatus 0 100 100 1 } } PROCESS { switch ($PsCmdlet.ParameterSetName) { "Path" { $resolvedSourcePaths = GetResolvedPathHelper $Path $false $PSCmdlet if ($resolvedSourcePaths.Count -gt 1) { $errorMessage = ($LocalizedData.InvalidArchiveFilePathError -f $Path, $PsCmdlet.ParameterSetName, $PsCmdlet.ParameterSetName) ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $Path } } "LiteralPath" { $resolvedSourcePaths = GetResolvedPathHelper $LiteralPath $true $PSCmdlet if ($resolvedSourcePaths.Count -gt 1) { $errorMessage = ($LocalizedData.InvalidArchiveFilePathError -f $LiteralPath, $PsCmdlet.ParameterSetName, $PsCmdlet.ParameterSetName) ThrowTerminatingErrorHelper "InvalidArchiveFilePath" $errorMessage ([System.Management.Automation.ErrorCategory]::InvalidArgument) $LiteralPath } } } ValidateArchivePathHelper $resolvedSourcePaths if ($pscmdlet.ShouldProcess($resolvedSourcePaths)) { $expandedItems = @() try { # StopProcessing is not avaliable in Script cmdlets. However the pipleline execution # is terminated when ever 'CTRL + C' is entered by user to terminate the cmdlet execution. # The finally block is executed whenever pipleline is terminated. # $isArchiveFileProcessingComplete variable is used to track if 'CTRL + C' is entered by the # user. $isArchiveFileProcessingComplete = $false # The User has not provided a destination path, hence we use '$pwd\ArchiveFileName' as the directory where the # archive file contents would be expanded. If the path '$pwd\ArchiveFileName' already exists then we use the # Windows default mechanism of appending a counter value at the end of the directory name where the contents # would be expanded. if (!$isDestinationPathProvided) { $archiveFile = New-Object System.IO.FileInfo $resolvedSourcePaths $resolvedDestinationPath = Join-Path -Path $resolvedDestinationPath -ChildPath $archiveFile.BaseName $destinationPathExists = Test-Path -LiteralPath $resolvedDestinationPath -PathType Container if (!$destinationPathExists) { New-Item -Path $resolvedDestinationPath -ItemType Directory -Confirm:$isConfirm -Verbose:$isVerbose -ErrorAction Stop | Out-Null } } ExpandArchiveHelper $resolvedSourcePaths $resolvedDestinationPath ([ref]$expandedItems) $Force $isVerbose $isConfirm $isArchiveFileProcessingComplete = $true } finally { # The $isArchiveFileProcessingComplete would be set to $false if user has typed 'CTRL + C' to # terminate the cmdlet execution or if an unhandled exception is thrown. if ($isArchiveFileProcessingComplete -eq $false) { if ($expandedItems.Count -gt 0) { # delete the expanded file/directory as the archive # file was not completly expanded. $expandedItems | ForEach-Object { Remove-Item $_ -Force -Recurse } } } } } } } } if (-not $ExecutionContext.SessionState.InvokeCommand.GetCommand('Register-ArgumentCompleter','Function,Cmdlet')) { Function Get-GenericArgumentCompleter { param ( [string]$name, [object]$collection ) Register-ArgumentCompleter -ParameterName $name -ScriptBlock { param ( $commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter ) if ($collection) { foreach ($item in $collection) { New-CompletionResult -CompletionText $item -ToolTip $item } } } } } if (-not $ExecutionContext.SessionState.InvokeCommand.GetCommand('Register-ArgumentCompleter','Function,Cmdlet')) { ############################################################################# # # TabExpansionPlusPlus # # <# Copyright (c) 2013, Jason Shirk All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #> # Save off the previous tab completion so it can be restored if this module # is removed. $oldTabExpansion = $function:TabExpansion $oldTabExpansion2 = $function:TabExpansion2 [bool]$updatedTypeData = $false #region Exported utility functions for completers ############################################################################# # # Helper function to create a new completion results # function New-CompletionResult { param ([Parameter(ValueFromPipelineByPropertyName, Mandatory, ValueFromPipeline)] [ValidateNotNullOrEmpty()] [string] $CompletionText, [Parameter(Position = 1, ValueFromPipelineByPropertyName)] [string] $ToolTip, [Parameter(Position = 2, ValueFromPipelineByPropertyName)] [string] $ListItemText, [System.Management.Automation.CompletionResultType] $CompletionResultType = [System.Management.Automation.CompletionResultType]::ParameterValue, [switch] $NoQuotes = $false ) process { $toolTipToUse = if ($ToolTip -eq '') { $CompletionText } else { $ToolTip } $listItemToUse = if ($ListItemText -eq '') { $CompletionText } else { $ListItemText } # If the caller explicitly requests that quotes # not be included, via the -NoQuotes parameter, # then skip adding quotes. if ($CompletionResultType -eq [System.Management.Automation.CompletionResultType]::ParameterValue -and -not $NoQuotes) { # Add single quotes for the caller in case they are needed. # We use the parser to robustly determine how it will treat # the argument. If we end up with too many tokens, or if # the parser found something expandable in the results, we # know quotes are needed. $tokens = $null $null = [System.Management.Automation.Language.Parser]::ParseInput("echo $CompletionText", [ref]$tokens, [ref]$null) if ($tokens.Length -ne 3 -or ($tokens[1] -is [System.Management.Automation.Language.StringExpandableToken] -and $tokens[1].Kind -eq [System.Management.Automation.Language.TokenKind]::Generic)) { $CompletionText = "'$CompletionText'" } } return New-Object System.Management.Automation.CompletionResult ` ($CompletionText, $listItemToUse, $CompletionResultType, $toolTipToUse.Trim()) } } ############################################################################# # # .SYNOPSIS # # This is a simple wrapper of Get-Command gets commands with a given # parameter ignoring commands that use the parameter name as an alias. # function Get-CommandWithParameter { [CmdletBinding(DefaultParameterSetName = 'AllCommandSet')] param ( [Parameter(ParameterSetName = 'AllCommandSet', ValueFromPipeline, ValueFromPipelineByPropertyName)] [ValidateNotNullOrEmpty()] [string[]] ${Name}, [Parameter(ParameterSetName = 'CmdletSet', ValueFromPipelineByPropertyName)] [string[]] ${Verb}, [Parameter(ParameterSetName = 'CmdletSet', ValueFromPipelineByPropertyName)] [string[]] ${Noun}, [Parameter(ValueFromPipelineByPropertyName)] [string[]] ${Module}, [ValidateNotNullOrEmpty()] [Parameter(Mandatory)] [string] ${ParameterName}) begin { $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Get-Command', [System.Management.Automation.CommandTypes]::Cmdlet) $scriptCmd = { & $wrappedCmd @PSBoundParameters | Where-Object { $_.Parameters[$ParameterName] -ne $null } } $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin) $steppablePipeline.Begin($PSCmdlet) } process { $steppablePipeline.Process($_) } end { $steppablePipeline.End() } } ############################################################################# # function Set-CompletionPrivateData { param ( [ValidateNotNullOrEmpty()] [string] $Key, [object] $Value, [ValidateNotNullOrEmpty()] [int] $ExpirationSeconds = 604800 ) $Cache = [PSCustomObject]@{ Value = $Value ExpirationTime = (Get-Date).AddSeconds($ExpirationSeconds) } $completionPrivateData[$key] = $Cache } ############################################################################# # function Get-CompletionPrivateData { param ( [ValidateNotNullOrEmpty()] [string] $Key) if (!$Key) { return $completionPrivateData } $cacheValue = $completionPrivateData[$key] if ((Get-Date) -lt $cacheValue.ExpirationTime) { return $cacheValue.Value } } ############################################################################# # function Get-CompletionWithExtension { param ([string] $lastWord, [string[]] $extensions) [System.Management.Automation.CompletionCompleters]::CompleteFilename($lastWord) | Where-Object { # Use ListItemText because it won't be quoted, CompletionText might be [System.IO.Path]::GetExtension($_.ListItemText) -in $extensions } } ############################################################################# # function New-CommandTree { [CmdletBinding(DefaultParameterSetName = 'Default')] param ( [Parameter(Mandatory, ParameterSetName = 'Default')] [Parameter(Mandatory, ParameterSetName = 'Argument')] [ValidateNotNullOrEmpty()] [string] $Completion, [Parameter(Position = 1, Mandatory, ParameterSetName = 'Default')] [Parameter(Position = 1, Mandatory, ParameterSetName = 'Argument')] [string] $Tooltip, [Parameter(ParameterSetName = 'Argument')] [switch] $Argument, [Parameter(Position = 2, ParameterSetName = 'Default')] [Parameter(Position = 1, ParameterSetName = 'ScriptBlockSet')] [scriptblock] $SubCommands, [Parameter(Mandatory, ParameterSetName = 'ScriptBlockSet')] [scriptblock] $CompletionGenerator ) $actualSubCommands = $null if ($null -ne $SubCommands) { $actualSubCommands = [NativeCommandTreeNode[]](& $SubCommands) } switch ($PSCmdlet.ParameterSetName) { 'Default' { New-Object NativeCommandTreeNode $Completion, $Tooltip, $actualSubCommands break } 'Argument' { New-Object NativeCommandTreeNode $Completion, $Tooltip, $true } 'ScriptBlockSet' { New-Object NativeCommandTreeNode $CompletionGenerator, $actualSubCommands break } } } ############################################################################# # function Get-CommandTreeCompletion { param ($wordToComplete, $commandAst, [NativeCommandTreeNode[]] $CommandTree) $commandElements = $commandAst.CommandElements # Skip the first command element - it's the command name # Iterate through the remaining elements, stopping early # if we find the element that matches $wordToComplete. for ($i = 1; $i -lt $commandElements.Count; $i++) { if (!($commandElements[$i] -is [System.Management.Automation.Language.StringConstantExpressionAst])) { # Ignore arguments that are expressions. In some rare cases this # could cause strange completions because the context is incorrect, e.g.: # $c = 'advfirewall' # netsh $c firewall # Here we would be in advfirewall firewall context, but we'd complete as # though we were in firewall context. continue } if ($commandElements[$i].Value -eq $wordToComplete) { $CommandTree = $CommandTree | Where-Object { $_.Command -like "$wordToComplete*" -or $_.CompletionGenerator -ne $null } break } foreach ($subCommand in $CommandTree) { if ($subCommand.Command -eq $commandElements[$i].Value) { if (!$subCommand.Argument) { $CommandTree = $subCommand.SubCommands } break } } } if ($null -ne $CommandTree) { $CommandTree | ForEach-Object { if ($_.Command) { $toolTip = if ($_.Tooltip) { $_.Tooltip } else { $_.Command } New-CompletionResult -CompletionText $_.Command -ToolTip $toolTip } else { & $_.CompletionGenerator $wordToComplete $commandAst } } } } #endregion Exported utility functions for completers #region Exported functions ############################################################################# # # .SYNOPSIS # Register a ScriptBlock to perform argument completion for a # given command or parameter. # # .DESCRIPTION # Argument completion can be extended without needing to do any # parsing in many cases. By registering a handler for specific # commands and/or parameters, PowerShell will call the handler # when appropriate. # # There are 2 kinds of extensions - native and PowerShell. Native # refers to commands external to PowerShell, e.g. net.exe. PowerShell # completion covers any functions, scripts, or cmdlets where PowerShell # can determine the correct parameter being completed. # # When registering a native handler, you must specify the CommandName # parameter. The CommandName is typically specified without any path # or extension. If specifying a path and/or an extension, completion # will only work when the command is specified that way when requesting # completion. # # When registering a PowerShell handler, you must specify the # ParameterName parameter. The CommandName is optional - PowerShell will # first try to find a handler based on the command and parameter, but # if none is found, then it will try just the parameter name. This way, # you could specify a handler for all commands that have a specific # parameter. # # A handler needs to return instances of # System.Management.Automation.CompletionResult. # # A native handler is passed 2 parameters: # # param($wordToComplete, $commandAst) # # $wordToComplete - The argument being completed, possibly an empty string # $commandAst - The ast of the command being completed. # # A PowerShell handler is passed 5 parameters: # # param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) # # $commandName - The command name # $parameterName - The parameter name # $wordToComplete - The argument being completed, possibly an empty string # $commandAst - The parsed representation of the command being completed. # $fakeBoundParameter - Like $PSBoundParameters, contains values for some of the parameters. # Certain values are not included, this does not mean a parameter was # not specified, just that getting the value could have had unintended # side effects, so no value was computed. # # .PARAMETER ParameterName # The name of the parameter that the Completion parameter supports. # This parameter is not supported for native completion and is # mandatory for script completion. # # .PARAMETER CommandName # The name of the command that the Completion parameter supports. # This parameter is mandatory for native completion and is optional # for script completion. # # .PARAMETER Completion # A ScriptBlock that returns instances of CompletionResult. For # native completion, the script block parameters are # # param($wordToComplete, $commandAst) # # For script completion, the parameters are: # # param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) # # .PARAMETER Description # A description of how the completion can be used. # function Register-ArgumentCompleter { [CmdletBinding(DefaultParameterSetName = "PowerShellSet")] param ( [Parameter(ParameterSetName = "NativeSet", Mandatory)] [Parameter(ParameterSetName = "PowerShellSet")] [string[]] $CommandName = "", [Parameter(ParameterSetName = "PowerShellSet", Mandatory)] [string] $ParameterName = "", [Parameter(Mandatory)] [scriptblock] $ScriptBlock, [string] $Description, [Parameter(ParameterSetName = "NativeSet")] [switch] $Native) $fnDefn = $ScriptBlock.Ast -as [System.Management.Automation.Language.FunctionDefinitionAst] if (!$Description) { # See if the script block is really a function, if so, use the function name. $Description = if ($fnDefn -ne $null) { $fnDefn.Name } else { "" } } if ($MyInvocation.ScriptName -ne (& { $MyInvocation.ScriptName })) { # Make an unbound copy of the script block so it has access to TabExpansionPlusPlus when invoked. # We can skip this step if we created the script block (Register-ArgumentCompleter was # called internally). if ($fnDefn -ne $null) { $ScriptBlock = $ScriptBlock.Ast.Body.GetScriptBlock() # Don't reparse, just get a new ScriptBlock. } else { $ScriptBlock = $ScriptBlock.Ast.GetScriptBlock() # Don't reparse, just get a new ScriptBlock. } } foreach ($command in $CommandName) { if ($command -and $ParameterName) { $command += ":" } $key = if ($Native) { 'NativeArgumentCompleters' } else { 'CustomArgumentCompleters' } $tabExpansionOptions[$key]["${command}${ParameterName}"] = $ScriptBlock $tabExpansionDescriptions["${command}${ParameterName}$Native"] = $Description } } ############################################################################# # # .SYNOPSIS # Tests the registered argument completer # # .DESCRIPTION # Invokes the registered parameteter completer for a specified command to make it easier to test # a completer # # .EXAMPLE # Test-ArgumentCompleter -CommandName Get-Verb -ParameterName Verb -WordToComplete Sta # # Test what would be completed if Get-Verb -Verb Sta<Tab> was typed at the prompt # # .EXAMPLE # Test-ArgumentCompleter -NativeCommand Robocopy -WordToComplete / # # Test what would be completed if Robocopy /<Tab> was typed at the prompt # function Test-ArgumentCompleter { [CmdletBinding(DefaultParametersetName = 'PS')] param ( [Parameter(Mandatory, Position = 1, ParameterSetName = 'PS')] [string] $CommandName , [Parameter(Mandatory, Position = 2, ParameterSetName = 'PS')] [string] $ParameterName , [Parameter(ParameterSetName = 'PS')] [System.Management.Automation.Language.CommandAst] $commandAst , [Parameter(ParameterSetName = 'PS')] [Hashtable] $FakeBoundParameters = @{ } , [Parameter(Mandatory, Position = 1, ParameterSetName = 'NativeCommand')] [string] $NativeCommand , [Parameter(Position = 2, ParameterSetName = 'NativeCommand')] [Parameter(Position = 3, ParameterSetName = 'PS')] [string] $WordToComplete = '' ) if ($PSCmdlet.ParameterSetName -eq 'NativeCommand') { $Tokens = $null $Errors = $null $ast = [System.Management.Automation.Language.Parser]::ParseInput($NativeCommand, [ref]$Tokens, [ref]$Errors) $commandAst = $ast.EndBlock.Statements[0].PipelineElements[0] $command = $commandAst.GetCommandName() $completer = $tabExpansionOptions.NativeArgumentCompleters[$command] if (-not $Completer) { throw "No argument completer registered for command '$Command' (from $NativeCommand)" } & $completer $WordToComplete $commandAst } else { $completer = $tabExpansionOptions.CustomArgumentCompleters["${CommandName}:$ParameterName"] if (-not $Completer) { throw "No argument completer registered for '${CommandName}:$ParameterName'" } & $completer $CommandName $ParameterName $WordToComplete $commandAst $FakeBoundParameters } } ############################################################################# # # .SYNOPSIS # Retrieves a list of argument completers that have been loaded into the # PowerShell session. # # .PARAMETER Name # The name of the argument complete to retrieve. This parameter supports # wildcards (asterisk). # # .EXAMPLE # Get-ArgumentCompleter -Name *Azure*; function Get-ArgumentCompleter { [CmdletBinding()] param ([string[]] $Name = '*') if (!$updatedTypeData) { # Define the default display properties for the objects returned by Get-ArgumentCompleter [string[]]$properties = "Command", "Parameter" Update-TypeData -TypeName 'TabExpansionPlusPlus.ArgumentCompleter' -DefaultDisplayPropertySet $properties -Force $updatedTypeData = $true } function WriteCompleters { function WriteCompleter($command, $parameter, $native, $scriptblock) { foreach ($n in $Name) { if ($command -like $n) { $c = $command if ($command -and $parameter) { $c += ':' } $description = $tabExpansionDescriptions["${c}${parameter}${native}"] $completer = [pscustomobject]@{ Command = $command Parameter = $parameter Native = $native Description = $description ScriptBlock = $scriptblock File = if ($scriptblock.File) { Split-Path -Leaf -Path $scriptblock.File } } $completer.PSTypeNames.Add('TabExpansionPlusPlus.ArgumentCompleter') Write-Output $completer break } } } foreach ($pair in $tabExpansionOptions.CustomArgumentCompleters.GetEnumerator()) { if ($pair.Key -match '^(.*):(.*)$') { $command = $matches[1] $parameter = $matches[2] } else { $parameter = $pair.Key $command = "" } WriteCompleter $command $parameter $false $pair.Value } foreach ($pair in $tabExpansionOptions.NativeArgumentCompleters.GetEnumerator()) { WriteCompleter $pair.Key '' $true $pair.Value } } WriteCompleters | Sort-Object -Property Native, Command, Parameter } ############################################################################# # # .SYNOPSIS # Register a ScriptBlock to perform argument completion for a # given command or parameter. # # .DESCRIPTION # # .PARAMETER Option # # The name of the option. # # .PARAMETER Value # # The value to set for Option. Typically this will be $true. # function Set-TabExpansionOption { param ( [ValidateSet('ExcludeHiddenFiles', 'RelativePaths', 'LiteralPaths', 'IgnoreHiddenShares', 'AppendBackslash')] [string] $Option, [object] $Value = $true) $tabExpansionOptions[$option] = $value } #endregion Exported functions #region Internal utility functions ############################################################################# # # This function checks if an attribute argument's name can be completed. # For example: # [Parameter(<TAB> # [Parameter(Po<TAB> # [CmdletBinding(DefaultPa<TAB> # function TryAttributeArgumentCompletion { param ( [System.Management.Automation.Language.Ast] $ast, [int] $offset ) $results = @() $matchIndex = -1 try { # We want to find any NamedAttributeArgumentAst objects where the Ast extent includes $offset $offsetInExtentPredicate = { param ($ast) return $offset -gt $ast.Extent.StartOffset -and $offset -le $ast.Extent.EndOffset } $asts = $ast.FindAll($offsetInExtentPredicate, $true) $attributeType = $null $attributeArgumentName = "" $replacementIndex = $offset $replacementLength = 0 $attributeArg = $asts | Where-Object { $_ -is [System.Management.Automation.Language.NamedAttributeArgumentAst] } | Select-Object -First 1 if ($null -ne $attributeArg) { $attributeAst = [System.Management.Automation.Language.AttributeAst]$attributeArg.Parent $attributeType = $attributeAst.TypeName.GetReflectionAttributeType() $attributeArgumentName = $attributeArg.ArgumentName $replacementIndex = $attributeArg.Extent.StartOffset $replacementLength = $attributeArg.ArgumentName.Length } else { $attributeAst = $asts | Where-Object { $_ -is [System.Management.Automation.Language.AttributeAst] } | Select-Object -First 1 if ($null -ne $attributeAst) { $attributeType = $attributeAst.TypeName.GetReflectionAttributeType() } } if ($null -ne $attributeType) { $results = $attributeType.GetProperties('Public,Instance') | Where-Object { # Ignore TypeId (all attributes inherit it) $_.Name -like "$attributeArgumentName*" -and $_.Name -ne 'TypeId' } | Sort-Object -Property Name | ForEach-Object { $propType = [Microsoft.PowerShell.ToStringCodeMethods]::Type($_.PropertyType) $propName = $_.Name New-CompletionResult $propName -ToolTip "$propType $propName" -CompletionResultType Property } return [PSCustomObject]@{ Results = $results ReplacementIndex = $replacementIndex ReplacementLength = $replacementLength } } } catch { } } ############################################################################# # # This function completes native commands options starting with - or -- # works around a bug in PowerShell that causes it to not complete # native command options starting with - or -- # function TryNativeCommandOptionCompletion { param ( [System.Management.Automation.Language.Ast] $ast, [int] $offset ) $results = @() $replacementIndex = $offset $replacementLength = 0 try { # We want to find any Command element objects where the Ast extent includes $offset $offsetInOptionExtentPredicate = { param ($ast) return $offset -gt $ast.Extent.StartOffset -and $offset -le $ast.Extent.EndOffset -and $ast.Extent.Text.StartsWith('-') } $option = $ast.Find($offsetInOptionExtentPredicate, $true) if ($option -ne $null) { $command = $option.Parent -as [System.Management.Automation.Language.CommandAst] if ($command -ne $null) { $nativeCommand = [System.IO.Path]::GetFileNameWithoutExtension($command.CommandElements[0].Value) $nativeCompleter = $tabExpansionOptions.NativeArgumentCompleters[$nativeCommand] if ($nativeCompleter) { $results = @(& $nativeCompleter $option.ToString() $command) if ($results.Count -gt 0) { $replacementIndex = $option.Extent.StartOffset $replacementLength = $option.Extent.Text.Length } } } } } catch { } return [PSCustomObject]@{ Results = $results ReplacementIndex = $replacementIndex ReplacementLength = $replacementLength } } #endregion Internal utility functions ############################################################################# # # This function is partly a copy of the V3 TabExpansion2, adding a few # capabilities such as completing attribute arguments and excluding hidden # files from results. # function global:TabExpansion2 { [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')] param ( [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory, Position = 0)] [string] $inputScript, [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory, Position = 1)] [int] $cursorColumn, [Parameter(ParameterSetName = 'AstInputSet', Mandatory, Position = 0)] [System.Management.Automation.Language.Ast] $ast, [Parameter(ParameterSetName = 'AstInputSet', Mandatory, Position = 1)] [System.Management.Automation.Language.Token[]] $tokens, [Parameter(ParameterSetName = 'AstInputSet', Mandatory, Position = 2)] [System.Management.Automation.Language.IScriptPosition] $positionOfCursor, [Parameter(ParameterSetName = 'ScriptInputSet', Position = 2)] [Parameter(ParameterSetName = 'AstInputSet', Position = 3)] [Hashtable] $options = $null ) if ($null -ne $options) { $options += $tabExpansionOptions } else { $options = $tabExpansionOptions } if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet') { $results = [System.Management.Automation.CommandCompletion]::CompleteInput( <#inputScript#> $inputScript, <#cursorColumn#> $cursorColumn, <#options#> $options) } else { $results = [System.Management.Automation.CommandCompletion]::CompleteInput( <#ast#> $ast, <#tokens#> $tokens, <#positionOfCursor#> $positionOfCursor, <#options#> $options) } if ($results.CompletionMatches.Count -eq 0) { # Built-in didn't succeed, try our own completions here. if ($psCmdlet.ParameterSetName -eq 'ScriptInputSet') { $ast = [System.Management.Automation.Language.Parser]::ParseInput($inputScript, [ref]$tokens, [ref]$null) } else { $cursorColumn = $positionOfCursor.Offset } # workaround PowerShell bug that case it to not invoking native completers for - or -- # making it hard to complete options for many commands $nativeCommandResults = TryNativeCommandOptionCompletion -ast $ast -offset $cursorColumn if ($null -ne $nativeCommandResults) { $results.ReplacementIndex = $nativeCommandResults.ReplacementIndex $results.ReplacementLength = $nativeCommandResults.ReplacementLength if ($results.CompletionMatches.IsReadOnly) { # Workaround where PowerShell returns a readonly collection that we need to add to. $collection = new-object System.Collections.ObjectModel.Collection[System.Management.Automation.CompletionResult] $results.GetType().GetProperty('CompletionMatches').SetValue($results, $collection) } $nativeCommandResults.Results | ForEach-Object { $results.CompletionMatches.Add($_) } } $attributeResults = TryAttributeArgumentCompletion $ast $cursorColumn if ($null -ne $attributeResults) { $results.ReplacementIndex = $attributeResults.ReplacementIndex $results.ReplacementLength = $attributeResults.ReplacementLength if ($results.CompletionMatches.IsReadOnly) { # Workaround where PowerShell returns a readonly collection that we need to add to. $collection = new-object System.Collections.ObjectModel.Collection[System.Management.Automation.CompletionResult] $results.GetType().GetProperty('CompletionMatches').SetValue($results, $collection) } $attributeResults.Results | ForEach-Object { $results.CompletionMatches.Add($_) } } } if ($options.ExcludeHiddenFiles) { foreach ($result in @($results.CompletionMatches)) { if ($result.ResultType -eq [System.Management.Automation.CompletionResultType]::ProviderItem -or $result.ResultType -eq [System.Management.Automation.CompletionResultType]::ProviderContainer) { try { $item = Get-Item -LiteralPath $result.CompletionText -ErrorAction Stop } catch { # If Get-Item w/o -Force fails, it is probably hidden, so exclude the result $null = $results.CompletionMatches.Remove($result) } } } } if ($options.AppendBackslash -and $results.CompletionMatches.ResultType -contains [System.Management.Automation.CompletionResultType]::ProviderContainer) { foreach ($result in @($results.CompletionMatches)) { if ($result.ResultType -eq [System.Management.Automation.CompletionResultType]::ProviderContainer) { $completionText = $result.CompletionText $lastChar = $completionText[-1] $lastIsQuote = ($lastChar -eq '"' -or $lastChar -eq "'") if ($lastIsQuote) { $lastChar = $completionText[-2] } if ($lastChar -ne '\') { $null = $results.CompletionMatches.Remove($result) if ($lastIsQuote) { $completionText = $completionText.Substring(0, $completionText.Length - 1) + '\' + $completionText[-1] } else { $completionText = $completionText + '\' } $updatedResult = New-Object System.Management.Automation.CompletionResult ` ($completionText, $result.ListItemText, $result.ResultType, $result.ToolTip) $results.CompletionMatches.Add($updatedResult) } } } } if ($results.CompletionMatches.Count -eq 0) { # No results, if this module has overridden another TabExpansion2 function, call it # but only if it's not the built-in function (which we assume if function isn't # defined in a file. if ($oldTabExpansion2 -ne $null -and $oldTabExpansion2.File -ne $null) { return (& $oldTabExpansion2 @PSBoundParameters) } } return $results } ############################################################################# # # Main # Add-Type @" using System; using System.Management.Automation; public class NativeCommandTreeNode { private NativeCommandTreeNode(NativeCommandTreeNode[] subCommands) { SubCommands = subCommands; } public NativeCommandTreeNode(string command, NativeCommandTreeNode[] subCommands) : this(command, null, subCommands) { } public NativeCommandTreeNode(string command, string tooltip, NativeCommandTreeNode[] subCommands) : this(subCommands) { this.Command = command; this.Tooltip = tooltip; } public NativeCommandTreeNode(string command, string tooltip, bool argument) : this(null) { this.Command = command; this.Tooltip = tooltip; this.Argument = true; } public NativeCommandTreeNode(ScriptBlock completionGenerator, NativeCommandTreeNode[] subCommands) : this(subCommands) { this.CompletionGenerator = completionGenerator; } public string Command { get; private set; } public string Tooltip { get; private set; } public bool Argument { get; private set; } public ScriptBlock CompletionGenerator { get; private set; } public NativeCommandTreeNode[] SubCommands { get; private set; } } "@ # Custom completions are saved in this hashtable $tabExpansionOptions = @{ CustomArgumentCompleters = @{ } NativeArgumentCompleters = @{ } } # Descriptions for the above completions saved in this hashtable $tabExpansionDescriptions = @{ } # And private data for the above completions cached in this hashtable $completionPrivateData = @{ } } if ($isLinux -or $IsMacOs) { # Create a fake unblock-file function Unblock-File { [CmdletBinding()] param( [Parameter(ValueFromPipeline)] [string[]]$Path ) # do nothing } } |