这可以使用Expand-Archive cmdlet 来完成,它在 PowerShell 5 及更高版本中可用。 (可以通过 $PSVersionTable 变量检查 PowerShell 的版本。)
要将 zip 文件提取到特定文件夹,请使用以下语法:
Expand-Archive -Path 'ZipFile.zip' -DestinationPath 'ZipFolder'
或
Expand-Archive -LiteralPath 'ZipFile.zip' -DestinationPath 'ZipFolder'
如果使用-Path 参数,PowerShell 会将诸如*、?、[、] 等字符识别为通配符,这可能会导致包含 square- 的文件路径出现意外行为括号。
如果使用-LiteralPath 参数,PowerShell 不会将任何字符视为通配符。
假设您所有的 zip 文件和文件夹都遵循相同的命名模式,您可以使用这样的数组:
$Countries = @(
'France',
'USA',
'German'
'Italy',
'Danemark'
)
foreach ($Country in $Countries)
{
$ZipFilePath = $Country + 'Data.zip'
$DestinationPath = $Country + 'Folder'
Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}
如果您的文件和文件夹不遵循相同的命名模式,您可以使用字典(或 KeyValuePairs 的集合),如下所示:
$ZipFilesAndFolders = @{
'FranceData.zip' = 'FranceFolder'
'USAData.zip' = 'USAFolder'
'GermanData.zip' = 'GermanFolder'
'ItalyData.zip' = 'ItalyFolder'
'DanemarkData.zip' = 'DanemarkFolder'
}
foreach ($KeyAndValue in $ZipFilesAndFolders.GetEnumerator())
{
$ZipFilePath = $KeyAndValue.Key
$DestinationPath = $KeyAndValue.Value
Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}
使用 PowerShell 4(和 3)
如果您安装了 .Net Framework 4.5,则可以使用由 PowerShell 团队创建的Microsoft.PowerShell.Archive。
PowerShell 4 需要 .Net Framework 4.5,因此无需任何系统更改即可工作。
该模块可以在https://github.com/PowerShell/Microsoft.PowerShell.Archive找到。
使用的语法相同,函数为Expand-Archive,参数为-Path、-LiteralPath和-DestinationPath。
只需确保在使用之前已导入模块,这可以使用 Import-Module cmdlet 来完成,如下所示:
Import-Module -Name 'Microsoft.PowerShell.Archive' -Force
PowerShell 2
可以在此处找到 PowerShell 2 的解决方案:https://stackoverflow.com/a/37814462/9447234