透過 7-zip 以指定密碼壓縮檔案
以下主要提供我使用 powershell 來壓縮指定目錄下的所有 *.dll 的檔案(並且壓縮完後刪除檔案)
這個需要自己設定 Filter 及 7-zip 的 7z.exe 路徑
這篇文章主要是我留個紀錄
$Filter = [String]"*.dll"
$7zBin = [String]"C:\Program Files\7-Zip\7z.exe"
# 設定 ProcessStartInfo
Set-Location $ProcessDIR.FullName
$dirPath = Read-Host 'Enter Directory Path'
$ProcessDIR = [System.IO.DirectoryInfo]::new($dirPath)
#取得密碼
$SecurePassword = Read-Host 'Enter Password' -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword)
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $7zBin
# $pinfo.Arguments = [String]"a -t7z """ + $ProcessDIR.FullName + "\" + $fileNameWithExtension + ".7z"" -p""" + $password + """ -mhe """ + $ProcessDIR.FullName + "\" + $file.Name + """"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.CreateNoWindow = $true
$process = New-Object System.Diagnostics.Process
$process.StartInfo = $pinfo
#Setup Error Listener
$errEvent = Register-ObjectEvent -InputObj $process `
-Event "ErrorDataReceived" `
-Action `
{
param
(
[System.Object] $sender,
[System.Diagnostics.DataReceivedEventArgs] $e
)
Write-host $e.Data
}
#Setup Out Listener
$outEvent = Register-ObjectEvent -InputObj $process `
-Event "OutputDataReceived" `
-Action `
{
param
(
[System.Object] $sender,
[System.Diagnostics.DataReceivedEventArgs] $e
)
Write-Host $e.Data
}
# $process.BeginOutputReadLine()
# $process.BeginErrorReadLine()
$i = 0
Foreach ($file in $files = $ProcessDIR.GetFiles($Filter))
{
$fileNameWithExtension = $file.Name.Substring(0, $file.Name.Length - $file.Extension.Length)
$7zFile = [System.IO.FileInfo]::new($ProcessDIR.FullName + "\" + $fileNameWithExtension + ".7z")
$sourceFile = [System.IO.FileInfo]::new($ProcessDIR.FullName + "\" + $file)
# 如果 7z 檔案有存在的話
if($true -eq $7zFile.Exists)
{
$7zFile.Delete()
Write-Host "File $7zFile deleted." -ForegroundColor red -BackgroundColor white
}
Write-Host "File $sourceFile Process ..."
$process.StartInfo.Arguments = [String]"a -t7z """ + $7zFile.FullName + """ -p""" + $password + """ -mhe """ + $sourceFile.FullName + """"
# Start the process
[Void] $process.Start()
# Begin async read events
while (!$process.HasExited)
{
Start-Sleep -Milliseconds 250
}
$process.Close()
[System.IO.File]::Delete($sourceFile.FullName)
}
Get-EventSubscriber -Force | Unregister-Event -Force
Write-Host "Done."
留言
張貼留言