我正在使用一个脚本将下载文件夹中的所有zip解压缩到桌面上的目录中。我可以正常使用它,但是尝试过一个.zip文件,这给我带来了麻烦。
当尝试ExtractToDirectory时,它返回有2个参数,并且“提取到Zip条目将导致文件超出指定的目标目录”,我能够使用WinZip以及文件浏览器的Extract All来解压缩此.zip正确。我不知道可能是什么问题。
#Script to Unzip .zip files in downloads folder.
#$src = file you're unzipping, $dest = destination for contents
$src = 'C:\Users\' + $env:USERNAME + '\Downloads\'
$dest = 'C:\Users\' + $env:USERNAME + '\Desktop\Zips\'
Function UnZipper($src, $dest)
{
Add-Type -AssemblyName System.IO.Compression.FileSystem
#specifies zip files in directory
$zps = Get-ChildItem $src -Filter *.zip
#unpacks each zip in directory to destination folder
foreach ($zp IN $zps)
{
#Sets File Path of original zip
$Zips = ($src + $zp)
#Sets destination of zip. Creates folder if it does not exist.
$NewFolder = $dest + $zp
$NewFolder = $NewFolder.TrimEnd(".zip")
#Checks if file already exists (has been unzipped)
$FileExists = Test-Path $NewFolder
If ($FileExists -eq $false)
{
Write-Host 'UnZipping -'$zp
[System.IO.Compression.ZipFile]::ExtractToDirectory($Zips, $NewFolder)
}
}
}
UnZipper -src $src -dest $dest
Write-Host "Your files have been Un-Zipped!"
Write-Host "Press the enter key to exit and open your file(s)" -ForegroundColor Green
Read-Host
explorer $dest
如果特定的zip最终无法解决,那对我来说很好。我只是想弄清楚为什么它可以与WinZip一起使用,而不能与PowerShell一起使用。
答案 0 :(得分:0)
$zps = Get-ChildItem $src -Filter *.zip -File
生成一个FileInfo objects数组,您不应像在foreach循环中那样将它们视为简单的文件路径字符串。
最好在需要的地方使用Join-Path cmdlet构造路径:
在下面重新编写函数
function UnZipper {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string]$src,
[Parameter(Mandatory = $true, Position = 1)]
[string]$dest
)
Add-Type -AssemblyName System.IO.Compression.FileSystem
# get an array of FileInfo objects for zip files in the $src directory and loop through
Get-ChildItem $src -Filter *.zip -File | ForEach-Object {
# unpacks each zip in directory to destination folder
# the automatic variable '$_' here represents a single FileInfo object, each file at a time
# Get the destination folder for the zip file. Create the folder if it does not exist.
$destination = Join-Path -Path $dest -ChildPath $_.BaseName # $_.BaseName does not include the extension
# Check if the folder already exists
if (!(Test-Path $destination -PathType Container)) {
# create the destination folder
New-Item -Path $destination -ItemType Directory -Force | Out-Null
# unzip the file
Write-Host "UnZipping - $($_.FullName)"
[System.IO.Compression.ZipFile]::ExtractToDirectory($_.FullName, $destination)
}
else {
Write-Host "Folder '$destination' already exists. File skipped."
}
}
}