【发布时间】:2016-10-30 01:35:11
【问题描述】:
我需要从 zipfile 中解压缩特定目录。
例如,从 zipfile 'c:\tmp\test.zip' 中提取目录 'test\etc\script' 并将其放在 c:\tmp\output\test\etc\script 中。
下面的代码有效,但有两个怪癖:
虽然我已经知道路径('c:\tmp\test.zip\test\etc\script'),但我需要在 zip 文件(函数 finditem)中递归查找目录('script')
使用 CopyHere 我需要手动确定目标目录,特别是 'test\etc' 部分
有更好的解决方案吗?谢谢。
代码:
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)
【问题讨论】:
-
我知道位置,所以不得不递归查找目录看起来很可惜。 .NET 4.5 代码有效,但我不愿意添加另一个先决条件。
-
好吧,那么可以避免搜索和另一个先决条件,看我的回答。
标签: powershell