我使用Expand-Archive命令解压缩一些.zip文件。我希望这个过程生成一个日志,并且我正在尝试使用参数-PassThru。
Expand-Archive D:\Users\user1\Desktop\Zip\de23.zip -DestinationPath D:\Users\user1\Desktop\result -Force -PassThru结果:
展开-存档:找不到匹配参数名'PassThru‘的参数。
发布于 2022-10-21 12:36:13
作为Mathias的有用答案的补充,这里有一个解决方案,它使用-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>&1将冗长的流(由-Verbose创建)重定向(合并)到成功流(标准输出),这样我们就可以通过管道命令来处理它。见关于输出流。Select-String在每一行输出中搜索给定的RegEx模式。有关详细解释和实验能力,请参阅此RegEx101演示。Get-Item行中,路径是通过延迟绑定脚本块指定的。这个脚本块从当前的RegEx匹配中提取第一个组的值(文件路径)。Get-Item输出一个FileInfo对象,类似于新的PowerShell版本上的Expand-Archive -PassThru。这将导致默认的PowerShell格式化程序生成熟悉的目录列表。发布于 2022-10-21 12:18:38
正如注释中提到的,您所引用的文档是PowerShell的最新版本。对于 PowerShell (Version5.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 Disposehttps://stackoverflow.com/questions/74153109
复制相似问题