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 :

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 }


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

Leave a ReplyCancel reply