[英]How do I pass a collection of object types to a function as a parameter in PowerShell?
Here is my code: 这是我的代码:
function Get-OSInfo {
param([string]$Computer)
$OS = gwmi -class Win32_OperatingSystem -computer $Computer
$OS | Add-Member –MemberType NoteProperty –Name OSType –Value ""
$OS.OSType = Get-OSType -Input $OS
write $OS
}
function Get-OSType {
param([?]$Input)
if ($Input.ProductType -eq 1) {
write "Client OS"
}
}
$blah = Get-OSInfo -Computer mypc
$blah | fl *
I realize that this could be done with a single function (or in the body of the script itself), but I have simplified the functions to highlight the trouble I'm having. 我意识到可以使用单个函数(或在脚本本身中)完成此操作,但是我已经简化了函数以突出我遇到的麻烦。 What I want to do is pass the gwmi dataset from the Get-OSInfo function as a parameter variable in the Get-OSType so I can reference all of its properties in the second function without passing them individually from the first. 我想要做的是将Get-OSInfo函数中的gwmi数据集作为Get-OSType中的参数变量传递,这样我就可以在第二个函数中引用其所有属性,而不必从第一个函数中单独传递它们。 Clear as mud? 像泥一样清澈?
I have tried multiple parameter accelerator types, [ref]
, [array]
, [object[]]
, etc., but I haven't found anything that works as a parameter. 我尝试了多种参数加速器类型,例如[ref]
, [array]
, [object[]]
等,但是我还没有找到任何能用作参数的东西。 The only thing that has proven to work is to change the second function to use args[0]
for accepting input, but that is not as clean as using parameters, and since it works, I can't help but think there is a parameter that should work as well. 唯一有效的方法是更改第二个函数以使用args[0]
接受输入,但这并不像使用参数那样干净,并且由于它可以工作,所以我不禁认为有一个参数那也应该工作。
Avoid using $input
as that has special meaning in functions (representing pipeline input). 避免使用$input
,因为这在函数中具有特殊含义(代表管道输入)。 Just rename the parameter to something like $OS
. 只需将参数重命名为$OS
。
The docs (man about_automatic_variables) on $input
say: $input
上的文档(man about_automatic_variables)说:
Contains an enumerator that enumerates all input that is passed to a function. 包含一个枚举器,该枚举器枚举传递给函数的所有输入。 The $input variable is available only to functions and script blocks (which are unnamed functions). $ input变量仅对函数和脚本块(未命名的函数)可用。 In the Process block of a function, the $input variable enumerates the object that is currently in the pipeline. 在函数的Process块中,$ input变量枚举了当前在管道中的对象。 When the Process block completes, there are no objects left in the pipeline, so the $input variable enumerates an empty collection. 当Process块完成时,管道中没有任何对象,因此$ input变量枚举一个空集合。 If the function does not have a Process block, then in the End block, the $input variable enumerates the collection of all input to the function. 如果该函数没有Process块,则在End块中,$ input变量枚举该函数的所有输入的集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.