1

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?

1 Answer 1

3

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

$foo = Invoke-Command -ScriptBlock { ,@() }
Sign up to request clarification or add additional context in comments.

2 Comments

Can anyone comment on why this is necessary for Invoke-Command but not a typical function return call?
As I know powershell functions behave the same - the empty array will get flattened on return.

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.