为什么 ScriptBlock 将 Hashtable 转换为 Collection,以及如何避免它?



请考虑以下PowerShell脚本:

[Hashtable] $t = @{} 
function foo($x) { $x }
$t2 = foo $t
$t3 = {param([Hashtable] $x) [Hashtable]$x}.Invoke($t)
$t4 = $function:foo.Invoke($t)
Write-Host "argument type              " $t.GetType()
Write-Host "function call              " $t2.GetType()
Write-Host "script block Invoke        " $t3.GetType()
Write-Host "function variable Invoke   " $t4.GetType()

哪些输出:

argument type              System.Collections.Hashtable
function call              System.Collections.Hashtable
script block Invoke        System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]
function variable Invoke   System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]

为什么脚本块返回Collection而不是Hashtable
如何让脚本块返回Hashtable

使用的PowerShell版本:

$PSVersionTable
Name                           Value
----                           -----
PSVersion                      7.0.0
PSEdition                      Core
GitCommitId                    7.0.0
OS                             Microsoft Windows 10.0.18363
Platform                       Win32NT
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1
WSManStackVersion              3.0

看看InvokeReturnAsIs方法:

[Hashtable] $t = @{} 
function foo($x) { $x }
$t2 = foo $t
$t3 = {param([Hashtable] $foo) [Hashtable]$foo}.InvokeReturnAsIs($t)
Write-Host $t.GetType()
Write-Host $t2.GetType()
Write-Host $t3.GetType()

哪些输出:

System.Collections.Hashtable
System.Collections.Hashtable
System.Collections.Hashtable

它似乎给出了您正在寻找的结果,但文档没有提供太多信息

我相信由于调用ScriptBlock.Invoke方法,Hashtable被转换为Collection。其返回类型为System.Collections.ObjectModel.Collection<System.Management.Automation.PSObject>

看起来可以通过调用命令调用脚本块来规避这一点:

[Hashtable] $t = @{} 
$t5 = Invoke-Command -ScriptBlock {param([Hashtable] $x) [Hashtable]$x} -ArgumentList $t
$t6 = Invoke-Command -ScriptBlock $function:foo -ArgumentList $t
Write-Host "Invoke-Command on script block      " $t5.GetType()
Write-Host "Invoke-Command on function variable " $t6.GetType()

这输出:

Invoke-Command on script block        System.Collections.Hashtable
Invoke-Command on function variable   System.Collections.Hashtable

相关内容

  • 没有找到相关文章

最新更新