使用 ValueFromPipelineByPropertyName 从管道获取价值

hjo*_*lev 3 powershell pipeline

我在使用从管道获取值时遇到一些问题ValueFromPipelineByPropertyName

当我运行Get-Input -ComputerName 'PC-01' | Get-Datacmdlet时Get-Input,应仅返回计算机名称“PC-01”,而该Get-Data函数应返回“从 Get-Input 传递的值:PC-01”。相反,我收到此错误:

Get-Data :输入对象不能绑定到命令的任何参数
要么是因为该命令不采用管道输入,要么是输入及其
属性与采用管道输入的任何参数都不匹配。
行:1 字符:33
+ 获取输入-计算机名 PC-01 | 获取数据
+ ~~~~~~~~~
    + CategoryInfo : InvalidArgument: (PC-01:PSObject) [获取数据],ParameterBindingException
    + FullQualifiedErrorId :InputObjectNotBound,获取数据

我构建了这两个小示例 cmdlet,只是为了掌握使用管道的窍门。

function Get-Input {
    [CmdletBinding()]
    Param(
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true
        )]
        [string]$ComputerName
    )

    Process {
        Write-Output -InputObject $ComputerName
    }
}

function Get-Data {
    [CmdletBinding()]
    Param(
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true
        )]
        [string]$ComputerName
    )

    Process {
        Write-Output -InputObject "Value passed from Get-Input: $($ComputerName)."
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我更改$ComputerName$Name并运行以下命令,它会起作用:

PS C:\Users\frede> Get-Service -Name AdobeARMservice | Get-Data
Value passed from Get-Input: AdobeARMservice.
Run Code Online (Sandbox Code Playgroud)

如果我掌握了 PowerShell 中管道的概念,我应该能够运行以下命令Get-Input -ComputerName 'PC-01' | Get-Data并将 ComputerName 传递给Get-Data.

有什么我需要在某处声明的吗?

Mat*_*sen 8

正如名称 ( ValueFromPipelineByPropertyName) 所示,您告诉解析器根据属性名称绑定一个值。

Get-Input函数需要输出一个对象,该对象具有为其命名的属性ComputerName

function Get-Input
{
    [CmdletBinding()]
    param
    (
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true
        )]
        [string]$ComputerName
    )

    process
    {
        Write-Output $(New-Object psobject -Propert @{ComputerName = $ComputerName})
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

Get-Input -ComputerName 'PC-01' |Get-Data
Run Code Online (Sandbox Code Playgroud)

如果要Get-Data支持从 中输入计算机名称Get-Service,则必须添加一个与 中输出的对象类型上的适当属性名称相匹配的别名Get-Service,即。MachineName:

function Get-Data
{
    [CmdletBinding()]
    param
    (
        [Parameter(
            Mandatory = $true,
            ValueFromPipelineByPropertyName = $true
        )]
        [Alias('MachineName')]
        [string]$ComputerName
    )

    process
    {
        Write-Output -InputObject "Value passed from Get-Input: $($ComputerName)."
    }
}
Run Code Online (Sandbox Code Playgroud)

现在这两个都可以工作:

Get-Service -Name AdobeARMService |Get-Data
Get-Input -ComputerName PC-01 |Get-Data
Run Code Online (Sandbox Code Playgroud)