Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell Where-Object replace is not working

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') }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  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') }

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading