如何使用 Powershell 将 Set-Content 写入文件?

dww*_*n66 3 powershell file-io

我在 PowerShell 脚本中进行了许多字符串替换。

foreach ($file in $foo) {
    $outfile = $outputpath + $file
    $content = Get-Content ($file.Fullname) -replace 'foo','bar'
    Set-Content -path $outfile -Force -Value $content 
}
Run Code Online (Sandbox Code Playgroud)

我已经验证(通过$outfileand 的控制台日志记录$content,我没有在上面的代码中显示)正在选择正确的文件,正在-replace准确地更新内容,并且$outfile正在创建 s。但是,每个输出文件都是一个 0 字节的文件。该Set-Content行似乎没有将数据写入文件。我试过管道Set-ContentOut-File,但这只会给我一个错误。

当我更换Set-Content使用Out-File,我得到一个运行时错误Out-File : A parameter cannot be found that matches parameter name 'path'.,即使我能输出$outfile到控制台,并认为它是一个有效的路径。

是否有额外的步骤(例如 close-File 或 save-file 命令)我需要采取或不同的顺序,我需要通过管道将某些东西$content写入我的$outfile? 我缺少什么组件?

Tre*_*van 5

Out-Filecmdlet 没有-Path参数,但它有一个-FilePath参数。以下是如何使用它的示例:

Out-File -FilePath test.txt -InputObject 'Hello' -Encoding ascii -Append;
Run Code Online (Sandbox Code Playgroud)

您还需要将Get-Content命令括在括号中,因为它没有名为-replace.

(Get-Content -Path $file.Fullname) -replace 'foo','bar';
Run Code Online (Sandbox Code Playgroud)

我还建议将-Raw参数添加到Get-Content,以确保您只处理一行文本,而不是一组字符串([String]文本文件中的每行一个)。

(Get-Content -Path $file.Fullname -Raw) -replace 'foo','bar';
Run Code Online (Sandbox Code Playgroud)

没有足够的信息来完全了解正在发生的事情,但这里有一个完整的示例,说明我认为您正在尝试执行的操作:

# Create some dummy content (source files)
mkdir $env:SystemDrive\test;
1..5 | % { Set-Content -Path $env:SystemDrive\test\test0$_.txt -Value 'foo'; };

# Create the output directory
$OutputPath = mkdir $env:SystemDrive\test02;

# Get a list of the source files
$FileList = Get-ChildItem -Path $env:SystemDrive\test -Filter *.txt;

# For each file, get the content, replace the content, and 
# write to new output location
foreach ($File in $FileList) {
    $OutputFile = '{0}\{1}' -f $OutputPath.FullName, $File.Name;
    $Content = (Get-Content -Path $File.FullName -Raw) -replace 'foo', 'bar';
    Set-Content -Path $OutputFile -Value $Content;
}
Run Code Online (Sandbox Code Playgroud)