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 ?? @().
try wrap your command with an array operator @.
so it will be -
$array = @(@() | ForEach-Object { $_ })
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?System.Management.Automation.Internal.AutomationNull which will changed in a $Null only when it is assigned. Check this: @() |ForEach-Object { $_ } |ForEach-Object { 'Test' }.
$alwaysArray = @(@() | ForEach-Object { $_ })$a = ,(@() | ForEach-Object { $_ }). You can also do that on $null:$a = ,$null; $a.GetType()-->Object[]@() |ForEach-Object { $_ } |ForEach-Object { 'Test' }. In other words, it doesn't return a$Null, it returns aSystem.Management.Automation.Internal.AutomationNullwhich it changed in a$Nullwhen it is assigned to a variable. See: Everything you wanted to know about $null.