有意思的Alias参数

1. 最简单的方式,运行正常。

PS C:\> Get-Service -Name BITS -ComputerName localhost

 

2. 自己构造一个对象,试图通过管道将主机名传递下去,但是不行,因为-ComputerName只接受byPropertyName的方式,而命令中的PropertyName却叫做ID。

PS C:\> [PSCustomObject]@{ 'ID' = 'localhost' } | Get-Service -Name BITS
Get-Service : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
At line:1 char:43
+ [PSCustomObject]@{ 'ID' = 'localhost' } | Get-Service -Name BITS
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (@{ID=localhost}:PSObject) [Get-Service], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.GetServiceCommand

 

3. 有什么变通的办法呢?自己构造一个函数,然后就能随心所欲地定制PropertyName了;加上Alias参数还能进一步变化。

function g-s
{   [CmdletBinding()]
    Param (
      [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
      [Alias('ID')]
      [String]$Param1,
      [String]$Param2
    )
    Begin { }
    Process { Get-Service -ComputerName $Param1 -Name $Param2}
    End { }
}

PS C:\> [PSCustomObject]@{ 'Param1' = 'localhost' } | g-s -Param2 BITS

PS C:\> [PSCustomObject]@{ 'ID' = 'localhost' } | g-s -Param2 BITS

转载于:https://www.cnblogs.com/IvanChen/p/6491601.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值