将值传递给powershell函数时遇到问题

时间:2016-04-20 16:06:23

标签: powershell

我试图将LDAP查询(计算机)的结果传递到我的Powershell函数中。但是,该函数仅处理一个值。这是一些示例代码:

$('.col-lg-3.form-group').switchClass( "col-lg-3", "col-lg-8", 0)

当我跑步时:

Function Get-ComputerName {
    Param(
        [Alias('Computer','ComputerName','HostName')]
        [Parameter(
            Mandatory=$true,
            Position=0,
            ValueFromPipeline=$true
        )]
        [Object[]]$computers
    )
    if(-not($computers)) { Throw “You must supply at least one computer” }

    foreach($computer in $computers) {
        write-host $computer.Name
    }
}

结果只打印了一个计算机名称,但肯定应该有多个。救命!感谢。

1 个答案:

答案 0 :(得分:2)

使用管道将多个对象传递给函数时,请确保使用Begin,Process和End块。在构建了我自己的$ computers对象之后,我可以复制这个问题。

$computers = @()
$computers += New-Object -TypeName PSObject -Property @{
    Name = "Test"
    Note = "TestTest"
}
$computers += New-Object -TypeName PSObject -Property @{
    Name = "Test2"
    Note = "TestTest"
}
$computers += New-Object -TypeName PSObject -Property @{
    Name = "Test3"
    Note = "TestTest"
}
$computers | Get-InstalledSoftware

这会产生test3

解决方案是简单地用Process {}封装函数的内部结构,如下所示:

Function Get-InstalledSoftware {
    Param(
        [Alias('Computer','ComputerName','HostName')]
        [Parameter(
            Mandatory=$true,
            Position=0,
            ValueFromPipeline=$true
        )]
        [Object[]]$computers
    )
    Process {
        if(-not($computers)) { Throw “You must supply at least one computer” }

        foreach($computer in $computers) {
            write-host $computer.Name
        }
    }
}