我想将一些小档案、Zip 和 7z 包含到 PS1 中。例如,如何将存档放入 $string 中?或者将存档包含到脚本本身而不是单独的文件中的最佳方法是什么?谢谢!
我尝试过这个: https://github.com/AveYo/Compressed2TXT/blob/master/Compressed%202%20TXT.bat
首先将 ZIP 文件转换为 base-64,方法是在控制台中输入以下命令:
# Encode the ZIP as base-64 text file with a maximum line length of 120 chars
[convert]::ToBase64String([IO.File]::ReadAllBytes("$PWD/test.zip")) -replace ".{1,120}", "$&`n" | Set-Content test.zip.base64
将 .base64 文本文件的内容复制粘贴到 PowerShell 脚本中,并将其分配给变量
$zipBase64
# Base-64 encoded ZIP file, containing two files 'file1.txt' and 'file2.txt'
$zipBase64 = @'
UEsDBAoAAAAAANZbNVblYOeeBQAAAAUAAAAJAAAAZmlsZTEudHh0ZmlsZTFQSwMECgAAAAAA4Vs1Vl8x7gcFAAAABQAAAAkAAABmaWxlMi50eHRmaWxlMlBL
AQI/AAoAAAAAANZbNVblYOeeBQAAAAUAAAAJACQAAAAAAAAAICAAAAAAAABmaWxlMS50eHQKACAAAAAAAAEAGAC2cplqgy3ZAQAAAAAAAAAAAAAAAAAAAABQ
SwECPwAKAAAAAADhWzVWXzHuBwUAAAAFAAAACQAkAAAAAAAAACAgAAAsAAAAZmlsZTIudHh0CgAgAAAAAAABABgAPC3ydIMt2QEAAAAAAAAAAAAAAAAAAAAA
UEsFBgAAAAACAAIAtgAAAFgAAAAAAA==
'@
# 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
类直接从 内存流 中提取 ZIP 中的文件无需先编写中间 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
读取数据。请参阅 System.IO.Stream
了解从流中读取数据的可用方法。