使用 PowerShell 从 zipfile 中提取目录的最优雅方法? [英] Most elegant way to extract a directory from a zipfile using PowerShell?
问题描述
我需要从 zipfile 中解压缩特定目录.
I need to unzip a specific directory from a zipfile.
例如,从 zipfile 'c:\tmp\test.zip' 中提取目录 'test\etc\script' 并将其放在 c:\tmp\output\test\etc\script 中.
Like for example extract the directory 'test\etc\script' from zipfile 'c:\tmp\test.zip' and place it in c:\tmp\output\test\etc\script.
下面的代码有效,但有两个怪癖:
The code below works but has two quirks:
尽管我已经知道路径 ('c:\tmp\test.zip\test\etc\script'),但我需要递归地找到 zip 文件中的目录 ('script')(函数 finditem)
I need to recursively find the directory ('script') in the zip file (function finditem) although I already know the path ('c:\tmp\test.zip\test\etc\script')
使用 CopyHere 我需要手动确定目标目录,特别是 'test\etc' 部分
With CopyHere I need to determine the targetdirectory, specifically the 'test\etc' part manually
有更好的解决方案吗?谢谢.
Any better solutions? Thanks.
代码:
function finditem($items, $itemname)
{
foreach($item In $items)
{
if ($item.GetFolder -ne $Null)
{
finditem $item.GetFolder.items() $itemname
}
if ($item.name -Like $itemname)
{
return $item
}
}
}
$source = 'c:\tmp\test.zip'
$target = 'c:\tmp\output'
$shell = new-object -com shell.application
# find script folder e.g. c:\tmp\test.zip\test\etc\script
$item = finditem $shell.NameSpace($source).Items() "script"
# output folder is c:\tmp\output\test\etc
$targetfolder = Join-Path $target ((split-path $item.path -Parent) -replace '^.*zip')
New-Item $targetfolder -ItemType directory -ErrorAction Ignore
# unzip c:\tmp\test.zip\test\etc\script to c:\tmp\output\test\etc
$shell.NameSpace($targetfolder).CopyHere($item)
推荐答案
只要知道 zip 中的文件夹位置,就可以简化原代码:
As far as the folder location in a zip is known, the original code can be simplified:
$source = 'c:\tmp\test.zip' # zip file
$target = 'c:\tmp\output' # target root
$folder = 'test\etc\script' # path in the zip
$shell = New-Object -ComObject Shell.Application
# find script folder e.g. c:\tmp\test.zip\test\etc\script
$item = $shell.NameSpace("$source\$folder")
# actual destination directory
$path = Split-Path (Join-Path $target $folder)
if (!(Test-Path $path)) {$null = mkdir $path}
# unzip c:\tmp\test.zip\test\etc\script to c:\tmp\output\test\etc\script
$shell.NameSpace($path).CopyHere($item)
这篇关于使用 PowerShell 从 zipfile 中提取目录的最优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!