我发现在某些情况下,powershell 2.0 正在传递包含 PSObjects 的 Object[] 数组——而不是真正包含的类型——当作为参数传递给 .Net 代码时。我认为这是一个 powershell 2.0 错误,但我找不到任何相关信息。
$Source = @"
public static class DotNetTypeInfo
{
public static string TypeOfNthElement(object[] oa, int n)
{
return oa[n].GetType().ToString();
}
}
"@
Add-Type -TypeDefinition $Source -Language CSharp
$h = @{}
$h.foo = "bar"
#$h["foo"] = "bar" # uncomment this to fix! (Why?)
$testdata = @($h) # To .net, passed Object[] containing PSObject, not Hashtable!
# other examples that behave similarly badly - uncomment to try
$a = (1,2) # should result in an arry of System.Int32
function getA() { $a } # uncaptured value returned
function getB() { return $a } # explicit return
# $testdata = $a # this works fine
# $testdata = getA # also fine
# $testdata = getB # To .net, passed Object[] containing PSObject, not Int32!
Write-Host "From powershell"
' $testdata[0].GetType() ' + $testdata[0].GetType().ToString()
Write-Host "From .Net"
' TypeOfNthElement($testdata,0) ' + [DotNetTypeInfo]::TypeOfNthElement($testdata,0)
这打印:
From powershell
$testdata[0].GetType() System.Collections.Hashtable
From .Net
TypeOfNthElement($testdata,0) System.Management.Automation.PSObject
最后一行非常令人惊讶; C# 代码正在接收包含 PSObject
的 Object[]
而不是包含 Hashtable
的 Object[]
。这使得无法与不需要 PSObject 的现有 .Net 库一起使用。
奇怪的是,如果我使用 $h["foo"] = "bar"
而不是 $h.foo = "bar"
,我可以解决这个问题。
我也看到了类似的效果,具体取决于您如何从函数返回值 - 取消注释 getA
和 getB
示例以尝试。
根据要求 - 从 $psversiontable
中选择要点,为简洁起见进行了编辑:
Key : CLRVersion, Value : 2.0.50727.5472
Key : BuildVersion, Value : 6.1.7601.17514
Key : PSVersion, Value : 2.0
Key : PSCompatibleVersions, Value : {1.0, 2.0}
Key : SerializationVersion, Value : 1.1.0.1
我可以在 XP、Win7 和 Windows Server 2008 R2 上使用 powershell 2.0 重现这个问题
最佳答案
我使用 PowerShell V2.0 在 W2K3 Box 上测试了您的代码,第三次测试返回了 ["hello","world"]
。
如果 getdata3
看起来像这样,我会收到你的错误:
function getdata3()
{
$a
return " "
}
所以我的结论是你的脚本代码中有一些“隐藏”字符,在复制/过去这个问题时丢失了。
关于更多的事情:你能在你的 PowerShell 上给出 $psversiontable 的值吗?
关于.net - 为什么 powershell 有时会将 PSObject(而不是基础对象)传递给 .Net 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21635973/