Home > Software engineering >  Powershell Where-Object replace is not working
Powershell Where-Object replace is not working

Time:08-19

I'm trying to replace this object that has a string assigned for sorting as "zNo Creator Found" with "No Creator Found". I've tried several different ways but the string never gets replaced:

Where-Object { ($_.Creator -replace 'zNo Creator Found','No Creator Found') }

CodePudding user response:

  1. For modifying an object, you want to use ForEach-Object, which has a handy alias as %. While Where-Object would technically work in this case, it's confusing to code readers as Where-Object is intended for filtering a collection based on a condition. If you want to perform some action on each object of a collection, use ForEach-Object.

  2. .NET strings are immutable so you can't modify the string in place. You have to reassign the string.

ForEach-Object { $_.Creator = ($_.Creator -replace 'zNo Creator Found','No Creator Found') }

  • Related