![](/img/trans.png)
[英]Powershell Script : Unzip files and execute bat file within the zip files
[英]Embed ZIP files directly within a PowerShell script, not in a separate file
我想包括一些小檔案,Zip 和 7z 到 PS1。 例如,如何將存檔放入 $string 中? 或者將存檔包含到腳本本身而不是單獨文件中的最佳方法是什么? 謝謝!
我試過這個: https://github.com/AveYo/Compressed2TXT/blob/master/Compressed%202%20TXT.bat
首先將 ZIP 文件轉換為 base-64,方法是在控制台中輸入以下命令之一,具體取決於您的 PowerShell 版本:
# PowerShell 5.1
[convert]::ToBase64String((Get-Content 'test.zip' -Encoding byte)) |
Set-Content test.zip.base64 -NoNewline
# PowerShell Core 7+
[convert]::ToBase64String((Get-Content 'test.zip' -AsByteStream)) |
Set-Content test.zip.base64 -NoNewline
將 .base64 文本文件的內容復制粘貼到您的 PowerShell 腳本中並將其分配給變量$zipBase64
# Base-64 encoded ZIP file, containing two files 'file1.txt' and 'file2.txt'
$zipBase64 = 'UEsDBAoAAAAAANZbNVblYOeeBQAAAAUAAAAJAAAAZmlsZTEudHh0ZmlsZTFQSwMECgAAAAAA4Vs1Vl8x7gcFAAAABQAAAAkAAABmaWxlMi50eHRmaWxlMlBLAQI/AAoAAAAAANZbNVblYOeeBQAAAAUAAAAJACQAAAAAAAAAICAAAAAAAABmaWxlMS50eHQKACAAAAAAAAEAGAC2cplqgy3ZAQAAAAAAAAAAAAAAAAAAAABQSwECPwAKAAAAAADhWzVWXzHuBwUAAAAFAAAACQAkAAAAAAAAACAgAAAsAAAAZmlsZTIudHh0CgAgAAAAAAABABgAPC3ydIMt2QEAAAAAAAAAAAAAAAAAAAAAUEsFBgAAAAACAAIAtgAAAFgAAAAAAA=='
# Convert the base-64 string into a byte array
$zipByteArray = [convert]::FromBase64String( $zipBase64 )
# Write the byte array into a ZIP file within the current directory
$zipPath = Join-Path $PWD.Path 'output.zip'
[IO.File]::WriteAllBytes( $zipPath, $zipByteArray )
# Extract the ZIP file into sub directory 'files' of the current directory
$outputDir = (New-Item 'files' -ItemType Directory -Force).FullName
Expand-Archive -Path $zipPath -DestinationPath $outputDir
這是簡單的代碼,但並不總是需要創建中間 ZIP 文件。
如果你有一個不太舊的 PowerShell 版本(我相信你至少需要 PowerShell 5),你可以使用ZipArchive
class 直接從內存 stream中提取文件 stream 而無需先編寫中間件ZIP 文件。
# Create an in-memory ZipArchive from the $zipByteArray
$zipArchive = [IO.Compression.ZipArchive]::new( [IO.MemoryStream]::new( $zipByteArray ) )
# Create the output directory
$outputDir = (New-Item 'files' -ItemType Directory -Force).FullName
# For each entry in the ZIP archive
foreach( $entry in $zipArchive.Entries ) {
# Build full output path
$fullPath = Join-Path $outputDir $entry.FullName
if( $fullPath.EndsWith( [IO.Path]::DirectorySeparatorChar ) ) {
# This is a directory
$null = New-Item $fullPath -ItemType Directory -Force
}
else {
# Create output file
$fileStream = [IO.File]::OpenWrite( $fullPath )
try {
# Extract file from ZIP
$entryStream = $entry.Open()
$entryStream.CopyTo( $fileStream )
}
finally {
# Make sure to always close the output file otherwise
# you could end up with an incomplete file.
$fileStream.Dispose()
}
}
}
如果只想獲取 ZIP 中的文件內容,而不是將其解壓到磁盤文件中,則可以從上例中的$entryStream
中讀取數據。 有關從 stream 讀取數據的可用方法,請參閱System.IO.Stream
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.