如何使用PowerShell从ZIP深层子文件夹中复制.exe文件
解决PowerShell提取ZIP深层子文件夹中EXE文件的问题
我明白你的需求——你只想把ZIP文件里藏在4-5级子文件夹的EXE文件单独复制出来,而不是把整个ZIP内容都搬过去。你原来的代码会复制所有内容,是因为没有做文件过滤和深层文件夹的递归查找。下面给你两种实用的PowerShell方案:
方案1:基于Shell.Application的递归查找(无需临时解压)
这个方案直接操作ZIP文件内容,不用把整个ZIP解压到磁盘,适合处理大型ZIP文件:
# 定义路径,请替换为你的实际路径 $zipPath = "C:\Your\Source\File.zip" $destPath = "C:\Your\Destination\Folder" $shell = New-Object -ComObject shell.application $zip = $shell.Namespace((Resolve-Path $zipPath).Path) # 递归遍历ZIP内的所有文件和文件夹 function Get-ZipExeItems { param($items) foreach ($item in $items) { # 判断当前项目是EXE文件时,复制到目标文件夹 if (!$item.IsFolder -and $item.Path.EndsWith(".exe", [System.StringComparison]::OrdinalIgnoreCase)) { $shell.Namespace($destPath).CopyHere($item) Write-Host "已成功复制: $($item.Name)" } # 如果是文件夹,递归进入继续查找 if ($item.IsFolder) { Get-ZipExeItems $item.GetFolder.Items() } } } # 启动递归查找并复制 Get-ZipExeItems $zip.Items()
方案2:临时解压+筛选复制(PowerShell 5.0+适用)
如果你用的是Windows 10/Server 2016及以上系统(默认带PowerShell 5.0+),这个方案更直观易懂,步骤清晰:
# 定义路径,请替换为你的实际路径 $zipPath = "C:\Your\Source\File.zip" $destPath = "C:\Your\Destination\Folder" # 创建一个随机命名的临时文件夹,避免冲突 $tempExtractDir = Join-Path $env:TEMP "TempZip_$(Get-Random)" New-Item -ItemType Directory -Path $tempExtractDir | Out-Null try { # 把整个ZIP解压到临时文件夹 Expand-Archive -Path $zipPath -DestinationPath $tempExtractDir -Force # 递归查找所有EXE文件 $targetExes = Get-ChildItem -Path $tempExtractDir -Filter "*.exe" -Recurse -File if ($targetExes.Count -eq 0) { Write-Warning "在ZIP文件中没有找到任何EXE文件" } else { foreach ($exe in $targetExes) { Copy-Item -Path $exe.FullName -Destination $destPath -Force Write-Host "已复制文件: $($exe.Name)" } } } finally { # 不管成功失败,都清理临时文件夹 Remove-Item -Path $tempExtractDir -Recurse -Force -ErrorAction SilentlyContinue }
方案对比
- 方案1:无需磁盘临时空间,适合超大ZIP;但依赖COM对象,逻辑稍复杂。
- 方案2:代码更易读,调试方便;需要临时磁盘空间,适合大多数常规场景。
记得替换代码中的$zipPath和$destPath为你实际的文件/文件夹路径,同时确保你有目标文件夹的写入权限哦。
内容的提问来源于stack exchange,提问作者user584018
相关产品推荐
相关产品推荐

