在一条语句中修改和压缩文件

问题描述 投票:0回答:1

PS版本5.1.18362.2212

我想知道是否可以读取一组文本文件,修改其内容和文件名并将结果直接存储到 ZIP 文件中?

以下内容读取文本文件并修改它们,将更改存储到new文件中:

$xSource = "sourcefile.json"
$xTarget = "targetfile.json"
$replacement = "abc"
(Get-Content $xSource) | Foreach-Object {
  $_.replace('[XX]', $replacement).`
} | Set-Content -path $xTarget

是否可以修改此以将目标文件直接存储到 ZIP 文件中?

我希望像下面这样的东西会起作用,但我不确定如何将新文件名传递到 ZIP?或者以下是否有效?

$xSource = "sourcefile.json"
$xTarget = "targetfile.json"
$xTargetZip = "target.zip"
$replacement = "abc"
(Get-Content $xSource) | Foreach-Object {
  $_.replace('[XX]', $replacement).`
} | Compress-Archive -Update -DestinationPath $xTargetZip

我的印象是我需要将目标文件存储到临时文件夹中,然后从那里打包它们......有什么方法可以避免临时文件夹吗?

预先感谢您提供的任何和所有帮助。

powershell zip powershell-5.1 compress-archive c#-ziparchive
1个回答
3
投票

这个问题的解决方案很麻烦,但你要求它,这就是你如何将条目写入 zip 文件,而无需事先将 Json 的更新写入新文件,换句话说,将文件的内容 存储在内存中并且将它们写入 zip 条目

此处使用的 .NET 文档参考:

using namespace System.IO
using namespace System.IO.Compression

Add-Type -AssemblyName System.IO.Compression

try {    
    # be aware, DO NOT use relative paths here!
    $DestinationPath = 'path\to\test.zip'
    $destfs = [File]::Open($DestinationPath, [FileMode]::CreateNew)
    $zip    = [ZipArchive]::new($destfs, [ZipArchiveMode]::Update)

    Get-ChildItem -Path path\to\jsonfolder -Filter *.json | ForEach-Object {
        # `OpenText` uses UTF8 encoding, normally there shouldn't be any issues here
        # but you can also use `Get-Content` instead to get the file content
        $reader    = $_.OpenText()
        $content   = $reader.ReadToEnd() -replace 'hello', 'world'
        # this is yours to define, this is how each entry should be named
        $entryName = $_.BaseName + '-ToBeDetermined' + $_.Extension
        $zipEntry  = $zip.CreateEntry($entryName)
        $zipStream = $zipEntry.Open()
        $writer    = [StreamWriter]::new($zipStream)
        $writer.Write($content)
        $writer, $reader, $zipStream | ForEach-Object 'Dispose'
    }
}
finally {
    $zip, $destfs | ForEach-Object 'Dispose'
}

如果您希望简化上面演示的过程,读取 zip 存档并替换 zip 存档条目的内容,您可能会发现使用 PS压缩模块 会更容易(免责声明:我是作者)该模块的)。

这就是使用该模块的代码的样子:

$zip = New-Item 'path\to\test.zip' -ItemType File
Get-ChildItem -Path path\to\jsonfolder -Filter *.json | ForEach-Object {
    $entryName = $_.BaseName + '-ToBeDetermined' + $_.Extension
    ($_ | Get-Content -Raw) -replace 'hello', 'world' |
        New-ZipEntry -Destination $zip.FullName -EntryPath $entryName
}
© www.soinside.com 2019 - 2024. All rights reserved.