あまりこういうことしない仕事になってしまったのですが、たまたま、サーバーにunzipするためのソフトウェアをインストールするよう依頼をしている人がいましたので、ちょっと気になりました。
デフォルトでunzipできるのは、GUI操作に限ります。
よく考えると、.Net Framework 4.5からunzipができるようになったことを思い出しました。
そこで、追加でソフトウェアをインストールせず、以下ではどうかと提案してみました。
PowerShellのバージョンが5.0未満でも動作するようにしました。
なお、5.0からは、とても簡単になります。1行でできます。
以下を拡張子ps1のファイルとして、保存します。
function usage1 {
Write-Host "Usage: "$Script:MyInvocation.MyCommand.Name "<zip file name> <folder name to unzip>"
}
If($args.length -lt 2) {
usage1
exit 1
}
$strZip = $args[0]
$strPath = $args[1]
if(-Not(Test-Path $strZip)) {
Write-Host "Error " $strZip " does not exist."
exit 1
}
if(-Not(Test-Path $strPath)) {
Write-HOST "Error " $strPath " does not exist."
exit 1
}
[void][Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem")
$zippedFiles = [System.IO.Compression.ZipFile]::OpenRead($strZip).Entries
foreach($zippedFile in $zippedFiles) {
Write-Host $zippedFile
If (Test-Path (Join-Path $strPath $zippedFile.FullName)) {
$ParentPath = Split-Path (Join-Path $strPath $zippedFile.FullName) -Parent
Remove-Item -Path (Join-Path $strPath $zippedFile.FullName)
$strBasePath = Split-Path (Join-Path $strPath "aabbcc.cba") -Parent
While ($strBasePath -ne $ParentPath) {
If (((Get-Childitem $ParentPath | Measure-Object).Count) -eq 0) {
Remove-Item $ParentPath -Force
}
$ParentPath = Split-Path $ParentPath -Parent
}
}
}
[System.IO.Compression.ZipFile]::ExtractToDirectory($strZip, $StrPath)
Windows PowerShell 5.0のときの-Forceに相当することをしたいので、長くなりました。
ExtractToDirectoryに3番目にBoolean型を指定することができるはずですが、PowerShellではできないのかな。自分はできませんでした。単なる助言ですので、まあ、これでよいでしょう。
実行するとき、コマンドプロンプトとかからは、例えば以下でできます
Powershell -ExecutionPolicy RemoteSigned aaa.ps1 c:\ddd\aaa.zip c:\eee\fff
Windows PowerShell 5.0からは以下でできます
スクリプトファイルは不要です。
Powershell Expand-Archive -Path C:\ddd\aaa.zip.... -DestinationPath C:\eee\fff -Force