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 assignment in expression?

Does Powershell have an operator like Python’s :=, which can assign a variable within an expression? (e.g., if (match := pattern.search(data)) is not None)
Suppose I want to store a value in Powershell as a variable, but also pass it down the pipeline. Is there a more elegant way than …| ForEach-Object { $foo = $_.split(': ')[1]; $foo } |…?

>Solution :

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

You can use (...), the grouping operator to turn an assignment statement into an expression that passes the value being assigned through:

This allows you to simplify:

...| ForEach-Object { $foo = $_.split(': ')[1]; $foo }

to:

...| ForEach-Object { ($foo = $_.split(': ')[1]) }
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