从Power Shell社区扩展创建的ZIP文件中删除文件夹

时间:2014-01-22 21:48:25

标签: powershell

所有

我正在为PSv1使用Power Shell社区扩展,正在正确创建ZIP文件。但是,我只想要ZIP文件中的图像,我想从ZIP文件中删除该文件夹。

我有一个名为newpictures的文件夹,它已被压缩。然后,我使用Power Shell社区扩展中的-flattenpaths选项将所有图像放在基本路径中,但文件夹仍然存在。

我一直在网上寻找解决方案。我不确定我是否有这个权利,所以有人可以查看这些代码并在我继续之前告诉我这是否正确吗?

if (test-path $PSCXInstallDir) {
    write-zip -path "Microsoft.PowerShell.Core\FileSystem::$TestSite" -outputpath "Microsoft.PowerShell.Core\FileSystem::$ZipFileCreationDir\$ZipFileName" -noclobber -quiet -flattenpaths -level 9

    start-sleep -seconds 30

    if (test-path $ZipFileCreationDir\$ZipFileName) {
        $ShellApp = new-object -com shell.application
        $TheZipFile = $ShellApp.namespace("$ZipFileCreationDir\$ZipFileName")
        $TheZipFile.items() | where-object {$_.name -eq $FolderToCompress} | remove-item $FolderToCompress            
    }
}

变量是:

$PSCXInstallDir = "C:\Program Files\PowerShell Community Extensions"
$TestSite = "\\10.0.100.3\www2.varietydistributors.com\catalog\newpictures"
$ZipFileCreationDir = "\\10.0.100.3\www2.varietydistributors.com\catalog"
$ZipFileName = "vdi-test.zip"
$FolderToCompress = "newpictures"

提前感谢您的任何反馈。简而言之,我只想删除ZIP文件中的单个文件夹。

1 个答案:

答案 0 :(得分:0)

Remove-Item不适用于zip文件中的项目。在删除zip文件之前,您需要move要删除的对象:

$ShellApp = New-Object -COM 'Shell.Application'
$TheZipFile = $ShellApp.NameSpace("$ZipFileCreationDir\$ZipFileName")
$TheZipFile.Items() | ? { $_.Name -eq $FolderToCompress } | % {
  $ShellApp.NameSpace($env:TEMP).MoveHere($_)
  Remove-Item (Join-Path $env:TEMP $_.Name)
}

请注意Items()不会递归到嵌套文件夹中,它只枚举当前命名空间的文件和文件夹。如果需要处理嵌套文件夹的内容,则需要指定嵌套路径:

$NestedFolder = $ShellApp.NameSpace('C:\path\to\your.zip\nested\folder')

recurse有类似的内容:

function RecurseIntoZip($fldr) {
  $fldr.Items() | ? { $_.Name -eq $FolderToCompress } | % {
    $_.Name
  }
  $fldr.Items() | ? { $_.Type -eq 'File folder' } | % {
    RecurseIntoZip $_.GetFolder
  }
}

RecurseIntoZip $TheZipFile