PowerShell不识别命令-PassThru

8ulbf1ek  于 2022-11-10  发布在  Shell
关注(0)|答案(2)|浏览(238)

我正在使用Expand-Archive命令解压缩一些.zip文件。我希望这个过程生成一个日志,并且我正在尝试使用参数-PassThru。

Expand-Archive D:\Users\user1\Desktop\Zip\de23.zip -DestinationPath D:\Users\user1\Desktop\result -Force -PassThru

结果:
Expand-Archive:找不到与参数名‘PassThru’匹配的参数。
参考文献:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/expand-archive?view=powershell-7.2

mrwjdhj3

mrwjdhj31#

以下是对Mathias's helpful answer的补充,该解决方案使用-Verbose开关生成日志,然后从该日志中解析文件路径,以获得与较新PowerShell版本上的-PassThru相同的输出:

Expand-Archive ZipFile.zip -DestinationPath C:\ExtractDir -Force -Verbose 4>&1 | 
    Select-String -Pattern "Created '(.+)'" | 
    Get-Item -Path { $_.Matches.Groups[1].Value }
  • 4>&1Verbose流(由-Verbose创建)重定向(合并)到Success(标准输出)流中,因此我们可以通过管道命令进行处理。请参见About Output Streams
  • Select-String在输出的每一行中搜索给定的RegEx模式。请参阅RegEx101 demo以获得详细的解释和实验能力。
  • Get-Item行中,路径通过延迟绑定脚本块指定。此脚本块从当前的RegEx匹配中提取第一组的值(文件路径)。
  • Get-Item输出FileInfo对象,类似于较新PowerShell版本上的Expand-Archive -PassThru生成的对象。这会导致默认的PowerShell格式化程序生成熟悉的目录列表。
xurqigkl

xurqigkl2#

正如评论中提到的,您引用的文档是针对最新版本的PowerShell的。对于最新版本的WindowsPowerShell(5.1版),不存在-PassThru开关。
要解决此问题,您可以使用基础.NET API“手动”解压缩归档文件:

Add-Type -AssemblyName System.IO.Compression

$destination = "C:\destination\folder"

# Define log file name

$logFileName = "unpack-archive.log"

# Locate zip file

$zipFile = Get-Item C:\path\to\file.zip

"[$(Get-Date -F o)][INFO] Opening '$($zipFile.FullName)' to expand" |Add-Content $logFileName

# Open a read-only file stream

$zipFileStream = $zipFile.OpenRead()

# Instantiate ZipArchive

$zipArchive = [System.IO.Compression.ZipArchive]::new($zipFileStream)

# Iterate over all entries and pick the ones you like

foreach($entry in $zipArchive.Entries){
    try {
        "[$(Get-Date -F o)][INFO] Attempting to create '$($entry.Name)' in '${destination}'" |Add-Content $logFileName

        # Create new file on disk, open writable stream
        $targetFileStream = $(
            New-Item -Path $destination -Name $entry.Name -ItemType File
        ).OpenWrite()

        "[$(Get-Date -F o)][INFO] Attempting to copy '$($entry.Name)' to target file" |Add-Content $logFileName
        # Open stream to compressed file, copy to new file stream
        $entryStream = $entry.Open()
        $entryStream.BaseStream.CopyTo($targetFileStream)
    }
    catch {
        "[$(Get-Date -F o)][ERROR] Failed to unpack '$($entry.Name)': ${_}" |Add-Content $logFileName
    }
    finally {
        # Clean up
        $targetFileStream,$entryStream |ForEach-Object Dispose
    }
}

# Clean up

$zipArchive,$zipFileStream |ForEach-Object Dispose

相关问题