简体   繁体   中英

Powershell if changed Set-Content

I have a PowerShell script that I use to change text in a number of files. The following script will work & changes the text as expected.

Get-ChildItem $FileFolder -Recurse |
select -ExpandProperty fullname |
foreach {
     (Get-Content $_) |
     ForEach-Object {$_ -replace $old $new } |
         Set-Content $_
     }

The problem is though, it changes every file that it opens, so everything has a timestamp of when the job was run even if nothing was changed.

I have tried something similar to what is here but it gives me an error:

The term 'if' is not recognized as the name of a cmdlet, function, etc...

Here is the code I am trying to run:

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 $_
          }
    }

I know that the code isn't right, but if I move it inside the ForEach-Object , it won't run either.

What I want to do is to use the Set-Content statement only if the contents of the file have changed. Would appreciate any thoughts as to how best to do this.

What you can do is look for the string before getting and setting content. Something like:

Get-ChildItem $FileFolder -Recurse |
select -ExpandProperty fullname |
foreach {
     If(Select-String -Path $_ -SimpleMatch $old -quiet){
          (Get-Content $_) |
          ForEach-Object {$_ -replace $old $new } |
              Set-Content $_
          }
     }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM