[英]Powershell if changed Set-Content
我有一个PowerShell脚本,我用它来更改许多文件中的文本。 以下脚本将按预期工作并更改文本。
Get-ChildItem $FileFolder -Recurse |
select -ExpandProperty fullname |
foreach {
(Get-Content $_) |
ForEach-Object {$_ -replace $old $new } |
Set-Content $_
}
但问题是,它会更改它打开的每个文件,因此所有内容都有一个时间戳,表明即使没有更改任务也会运行作业。
我尝试了类似于这里的东西,但它给了我一个错误:
The term 'if' is not recognized as the name of a cmdlet, function, etc...
这是我试图运行的代码:
Get-ChildItem $FileFolder -Recurse |
select -ExpandProperty fullname |
foreach {
$b = ($a = Get-Content $_) |
ForEach-Object {$_ -replace $old $new } |
if (Compare $a $b -PassThru) {
$b | Set-Content $_
}
}
我知道代码不对,但如果我在ForEach-Object
移动它,它也不会运行。
我想要做的是只有在文件内容发生变化时才使用Set-Content
语句。 对于如何最好地做到这一点,我们将不胜感激。
您可以做的是在获取和设置内容之前查找字符串。 就像是:
Get-ChildItem $FileFolder -Recurse |
select -ExpandProperty fullname |
foreach {
If(Select-String -Path $_ -SimpleMatch $old -quiet){
(Get-Content $_) |
ForEach-Object {$_ -replace $old $new } |
Set-Content $_
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.