【发布时间】:2014-02-01 17:13:56
【问题描述】:
考虑以下代码。我只是通过使用-InputObject 参数将一个32 位有符号整数数组[Int32[]] 传递到Start-Job cmdlet。
$Job = Start-Job -ScriptBlock { $input.GetType().FullName; } -InputObject @(1,2,3);
Wait-Job -Job $Job;
Receive-Job -Keep $Job;
这段代码的结果是:
System.Management.Automation.Runspaces.PipelineReader`1+<GetReadEnumerator>d__0[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
查看PipelineReader .NET class 的文档,它有一个ReadToEnd() 方法。因此,下面的代码应该可以工作:
$Job = Start-Job -ScriptBlock { $input.ReadToEnd(); } -InputObject @(1,2,3);
Wait-Job -Job $Job;
Receive-Job -Keep $Job;
但是,我收到一条错误消息:
方法调用失败,因为 [System.Int32] 不包含名为“ReadToEnd”的方法。 + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound + PSComputerName : 本地主机
那么我想,我将只使用PSBase 属性来获取“真实”对象。
$Job = Start-Job -ScriptBlock { $input.psbase.ReadToEnd(); } -InputObject @(1,2,3);
Wait-Job -Job $Job;
Receive-Job -Keep $Job;
然后我收到类似的错误消息:
方法调用失败,因为 [System.Management.Automation.PSInternalMemberSet] 不包含名为“ReadToEnd”的方法。 + CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound + PSComputerName : 本地主机
我注意到围绕这种混乱有一个Microsoft Connect bug filed,但它让我更加困惑。显然PipelineReader 类有一个名称混淆的属性<>4__this,它有一个Read() 方法,使用Get-Member 是看不到的。
底线:当通过Start-Job cmdlet 上的-InputObject 参数提交输入时,有谁知道如何简单地“解包”$input 自动变量的内容,所以我可以单独处理这些对象吗?
这个脚本应该只返回1,而不是1, 2, 3。
$Job = Start-Job -ScriptBlock { $input[0]; } -InputObject @(1,2,3);
Wait-Job -Job $Job;
Receive-Job -Keep $Job;
【问题讨论】:
-
$Job = Start-Job -ScriptBlock { $($input)[0]; } -InputObject @(1,2,3)适合你吗? -
是的,但您能进一步解释一下
$input是什么吗?这就是我最终想要理解的。 -
我想我有一个更好的例子。 about_Automatic_Variables 在枚举器中表示
$input,您不能像数组一样对其进行索引。试试这个:$Job = Start-Job -ScriptBlock { $input.getEnumerator()[0] } -InputObject @(1,2,3)
标签: powershell windows-8.1 powershell-4.0