mardi 4 mai 2021

Hybrid Where-Object/ForEach-Object syntax

How do I elegantly crossbreed Where-Object with ForEach-Object?

The Where-Object cmdlet, has a very elegant way to filter objects: Which use to be the syntax:

... | Where-Object { $_.Id -eq 2 } | ...

Can now be written as:

... | Where-Object Id -eq 2 | ...

I am looking for a similar pipeline conditional statement but instead of filtering the objects in the pipeline, I want to change the concerned objects in the pipeline, like this:

... |ForEach-Object { if ($_.Id -eq 2) { $_.Name = 'test' }; $_ } | ...

In other words, is there a way to write the above syntax with less brackets, parenthesis and current object ($_) references. Like in the self-answer but without using a additional function?

Aucun commentaire:

Enregistrer un commentaire