[英]How do I write Set-Content to a file using Powershell?
我正在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
,但这给我一个错误。
将Set-Content
替换为Out-File
,出现运行时错误Out-File : A parameter cannot be found that matches parameter name 'path'.
即使我可以将$outfile
输出到控制台,并看到它是有效路径。
是否需要执行其他步骤(如close-File或save-file命令),或者是否需要以其他顺序传递$content
以使$content
写入$outfile
? 我缺少什么组件?
Out-File
cmdlet没有-Path
参数,但是有-FilePath
参数。 这是一个如何使用它的示例:
Out-File -FilePath test.txt -InputObject 'Hello' -Encoding ascii -Append;
您还需要将Get-Content
命令包装在括号中,因为它没有名为-replace
的参数。
(Get-Content -Path $file.Fullname) -replace 'foo','bar';
我还建议将-Raw
参数添加到Get-Content
,以确保仅处理一行文本,而不是字符串数组(文本文件中每行一个[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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.