1

Why does the expression @() | ForEach-Object { $_ } evaluate to $null? I would expect it to return an empty array.

Is there a short expression to coalesce $null to an empty array for PowerShell 5? In PowerShell 7 I can do $array ?? @().

5
  • 2
    Simply wrap your pipeline in another array-subexpression: $alwaysArray = @(@() | ForEach-Object { $_ }) Commented Jan 26, 2022 at 13:02
  • 2
    Consider what your example does; it passes nothing to the pipeline. Foreach-Object has no objects to iterate over. Commented Jan 26, 2022 at 13:21
  • Thanks for answering the second question. But still I am wondering why PowerShell behaves the way it does. In every other language I know, mapping an empty list still results in an empty list. Commented Jan 26, 2022 at 13:41
  • Or use the unary comma operator to wrap the emty array in a new single-element array. Upon return, PowerShell will unwrap the surrounding array leaving you with the inner (empty) array. $a = ,(@() | ForEach-Object { $_ }). You can also do that on $null: $a = ,$null; $a.GetType() --> Object[] Commented Jan 26, 2022 at 14:17
  • Check this: @() |ForEach-Object { $_ } |ForEach-Object { 'Test' }. In other words, it doesn't return a $Null, it returns a System.Management.Automation.Internal.AutomationNull which it changed in a $Null when it is assigned to a variable. See: Everything you wanted to know about $null. Commented Feb 3, 2022 at 9:07

1 Answer 1

2

try wrap your command with an array operator @.

so it will be -

$array = @(@() | ForEach-Object { $_ })
Sign up to request clarification or add additional context in comments.

2 Comments

This only works because ForEach-Object returns a void object. If it would actually return $null, $array would have 1 element. Is there a similar construct that also works for $null?
I downvoted this answer because it doesn't answer the question "Why does the expression @() | ForEach-Object { $_ } evaluate to $null?". In fact, it returns an Emprty Null, a System.Management.Automation.Internal.AutomationNull which will changed in a $Null only when it is assigned. Check this: @() |ForEach-Object { $_ } |ForEach-Object { 'Test' }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.