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

4

我正在编写一个PowerShell脚本,需要进行多个字符串替换。

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

我已经通过控制台记录$outfile$content(上面的代码中没有显示),验证了正确的文件被选中,-replace准确地更新了内容,并且$outfile已经创建。然而,每个输出文件都是0字节文件。Set-Content行似乎没有将数据写入文件。我尝试将Set-Content管道传输到Out-File,但这只会给我一个错误。
当我用Out-File替换Set-Content时,我收到一个运行时错误Out-File:找不到与参数名称“path”匹配的参数。,即使我可以将$outfile输出到控制台并查看它是有效路径。
是否有其他步骤(例如关闭文件或保存文件命令)需要执行,或者需要以不同的顺序传输某些内容才能让$content写入$outfile?我缺少哪个组件?

你验证了$content是否具有适当的内容吗? - sha
是的...我已经添加了 -replace 并准确地修改了内容,当我将 $content 记录到控制台时... - dwwilson66
在这行代码中:$content = Get-Content -replace 'foo','bar',你好像忘了告诉它从哪里获取内容。我猜这可能会解释为什么文件大小为0字节。 - mjolinor
那仍然无法工作。它会认为-replace是Get-Content的一个参数。我会使用:$content = (Get-Content $file.Fullname) -replace 'foo','bar' - mjolinor
@sha $file 是仅有的文件名,而$outfile则将路径附加到文件头以供输出。这个新建的文件大小为零字节。如果我理解正确,$file.Fullname 引用了源文件的完整路径,根据控制台输出显示,它似乎被正确地读取了。 - dwwilson66
显示剩余4条评论
1个回答

5
Out-File 命令没有 -Path 参数,但是它有一个 -FilePath 参数。以下是如何使用它的示例:
Out-File -FilePath test.txt -InputObject 'Hello' -Encoding ascii -Append;

您还需要将Get-Content命令用括号包装,因为它没有名为-replace的参数。

(Get-Content -Path $file.Fullname) -replace 'foo','bar';

我建议在 Get-Content 命令中添加 -Raw 参数,这样你就能确保只处理单行文本,而不是一个字符串数组(文本文件中每行一个 [String])。

(Get-Content -Path $file.Fullname -Raw) -replace 'foo','bar';

目前没有足够的信息来完全理解正在发生的事情,但这里有一个填写好的示例,我认为这是您尝试做的:

# 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接