Search code examples
powershellinvoke-command

How to make Invoke-Command return empty array instead of null when run script block


I am creating a function and sometimes, it will return a empty array as there is not result. This function may need to run with Invoke-Command for some scenario, such as run on a remote PC and etc.

But what i found that, when my function run under Invoke-Command with script block, it cannot return empty array, but just null.

So I have a try and find that, the Invoke-Command seems to not able to return empty array even though I do that explicitly.

For exmaple:

> $foo = @()
> $foo.GetType()

IsPublic IsSerial Name                                     BaseType                                          
-------- -------- ----                                     --------                                          
True     True     Object[]                                 System.Array 

> $foo = Invoke-Command -ScriptBlock { @() }
> $foo.GetType()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $foo.GetType()
+ ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

> $foo -eq $null
True

So how can I return empty array in this scenario? Any mistake here? Or any trick here?


Solution

  • Just prepend the returning value with comma , (array construction operator). Then the return value will not get flattened into $null:

    $foo = Invoke-Command -ScriptBlock { ,@() }