【问题标题】:having trouble piping values into powershell function无法将值通过管道传输到 powershell 函数中
【发布时间】:2016-04-20 16:06:22
【问题描述】:

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

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
    }
}

当我跑步时:

Get-ADComputer -SearchBase 'OU="Devices",dc=FVWM1,dc=Local' -Filter '*' | Get-ComputerName

结果只打印了一个计算机名称,但肯定不止一个。帮助!谢谢。

【问题讨论】:

  • 你确定函数只处理第一个值而不是最后一个值吗?
  • 也许我应该说“一个值”而不是“第一个值”,因为从技术上讲,我不确定用 write-host 写出的那个落在哪里。

标签: powershell


【解决方案1】:

使用管道将多个对象传递给函数时,请确保使用 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
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-12-05
    • 2021-08-04
    • 2015-03-30
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多