gpt4 book ai didi

powershell - 运行脚本 block 时如何使Invoke-Command返回空数组而不是null

转载 作者:行者123 更新时间:2023-12-03 01:07:44 26 4
gpt4 key购买 nike

我正在创建一个函数,有时,由于没有结果,它将返回一个空数组。在某些情况下,例如在远程PC等上运行,此功能可能需要使用Invoke-Command运行。

但是我发现,当我的函数在带有脚本块的Invoke-Command下运行时,它不能返回空数组,而只能返回null

因此,我尝试发现,即使我明确地执行了操作,Invoke-Command似乎也无法返回空数组。

例如:

> $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

那么在这种情况下如何返回空数组呢?这里有什么错误吗?还是这里有什么窍门?

最佳答案

只需在返回值前加上逗号,(数组构造运算符)。然后,返回值将不会变平为$null:

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

关于powershell - 运行脚本 block 时如何使Invoke-Command返回空数组而不是null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45275775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com