【问题标题】:PowerShell: How to copy only ".exe" file from ZIP folder to another folderPowerShell:如何仅将“.exe”文件从 ZIP 文件夹复制到另一个文件夹
【发布时间】:2018-10-12 19:07:48
【问题描述】:

我有一个“ZIP”文件,当我们提取它时,我们有 1 个“EXE”文件,位于 4-5 个子文件夹深度级别内。

我想获取那个“EXE”文件并复制到另一个文件夹中。如何使用 PowerShell?

我在下面尝试过,但它会复制所有 ZIP 内容,

 $shell = New-Object -ComObject shell.application
 $zip = $shell.NameSpace("Source Path")
 foreach ($item in $zip.items()) {
   $shell.Namespace("Destination Path").CopyHere($item)
} 

【问题讨论】:

  • 1) 解压zip文件到某个目录; 2)使用Get-ChildItem-Filter-Recurse定位.exe文件; 3)管道到Copy-Item并指定目的地。
  • 如果您不提取整个 zip 文件,您可能需要创建一个函数,您可以递归调用该函数来爬取 zip 中的文件夹,以便能够找到 exe 文件以便仅提取该文件。

标签: powershell


【解决方案1】:

简单的 sn-p 即可完成您的工作

#Sets the variable to the Source folder, recurse drills down to folders within

$Source = get-childitem "C:\Users" -recurse   #"C:\Users" an example

#Filters by extension .exe
$List = $Source | where {$_.extension -eq ".exe"}

#Copies all the items to the specified destination
$List | Copy-Item -Destination "C:\Scripts"   #"C:\Scripts" an example

上面的模块会扫描 C:\Users* 中的每个 .EXE 文件并将它们复制到 C:\Scripts

【讨论】:

    【解决方案2】:

    就目前而言,克林特的回答对我不起作用,但基于Extract Specific Files from ZIP Archive 的东西可以,但有一个变体以针对特定命名的文件。需要进一步调整以处理多个同名文件。

    代码:

    # Set source zip path, target output directory and file name filter
    
    $ZipPath = 'C:\temp\Test.zip'
    $OutDir = 'C:\temp'
    $Filter = 'MyExe.exe'
    
    # Load compression methods
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    
    # Open zip file for reading
    $Zip = [System.IO.Compression.ZipFile]::OpenRead($Path)
    
    # Copy selected items to the target directory
    $Zip.Entries | 
        Where-Object { $_.FullName -eq $Filter } | 
        ForEach-Object { 
            # Extract the selected items from the zip archive
            # and copy them to the out folder
            $FileName = $_.Name
            [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "$OutDir\$FileName", $true)
        }
    
    # Close zip file
    $Zip.Dispose()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多