【问题标题】:Remove Folder from ZIP file created by Power Shell Community Extensions从 Powershell 社区扩展创建的 ZIP 文件中删除文件夹
【发布时间】:2014-01-23 22:33:44
【问题描述】:

全部,

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

我有一个名为 newpictures 的文件夹,它被压缩了。然后我使用 Power Shell Community Extensions 中的 -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 文件中的单个文件夹。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    Remove-Item 不适用于 zip 文件中的项目。您需要先move zip 文件之外要删除的对象,然后才能删除它们:

    $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
    

    【讨论】:

    • 那么,当您将 ZIP 文件内容移动到临时文件夹并删除该文件夹时,您是否必须在之后将文件放回 ZIP 文件中,还是自动完成? ZIP 文件中没有嵌套,因为 Power Shell 社区扩展中用于 write-zip 函数的 -flattenpaths 开关删除了嵌套。我也一直试图弄清楚我是否可以在 Power Shell Community Extensions 中执行 write-zip 并完全消除该文件夹。我还没有在这方面找到任何东西。
    • 我只是重新阅读了您的帖子,如果我理解正确(菜鸟),您只是将文件夹移到 ZIP 文件之外并将其删除,但其他内容仍在其中?
    • @user3013729 正确。
    • 我正在尝试您的代码,我被告知该文件夹已经包含一个名为 $FolderToCompress (newpictures) 的文件夹,它询问我是否要移动或复制该文件夹(是的,是全部,不,取消)。查看临时目录 ($env:TEMP) 时,我根本看不到这个文件夹?
    • @user3013729 你看起来怎么样? cd $env:TEMP; Get-Item newpictures 产生什么输出?
    猜你喜欢
    • 1970-01-01
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多