【发布时间】:2014-08-30 21:54:36
【问题描述】:
我正在尝试使用CmdletBinding 和ValueFromPipeline 复制管道中可用的典型powershell -Computername 参数并作为普通参数。我的挑战是,我从指定参数与值中的管道得到不同的结果。
我的代码如下所示:
[CmdletBinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true)] [string[]]$ComputerName
)
BEGIN { "Begin script`n-----" }
PROCESS {
" `$ComputerName '$ComputerName'"
" `$_ '$_'"
" +++ Count: " + $ComputerName.Count
foreach($computer in $ComputerName) {
" `$computer '$computer'"
}
" -----"
}
END { "Complete" }
当我使用管道运行它时,我得到了这个:
PS> (1, 2, 3) | .\BPEParamTest.ps1 开始脚本 ----- $计算机名'1' $_ '1' +++ 计数:1 $计算机'1' ----- $计算机名'2' $_'2' +++ 计数:1 $计算机'2' ----- $计算机名'3' $_'3' +++ 计数:1 $电脑'3' ----- 完全的但是,当使用参数运行时,我会得到不同的结果:
PS> .\BPEParamTest.ps1 -计算机名 (1, 2, 3) 开始脚本 ----- $计算机名'1 2 3' $_'' +++ 计数:3 $计算机'1' $计算机'2' $电脑'3' ----- 完全的【问题讨论】:
-
我希望有人能给出一个好的答案。几天来,我也一直在努力解决这个问题。我注意到,如果我没有 Begin/Process/End 块并且只是将代码包含在基本函数中,它的行为也会有所不同,所以我认为它与块有关。
-
所以我的最终结果是终止管道使用,并使用基于参数的计算机名数组。这最终更符合几个内置命令的工作方式,例如 get-service(管道是服务名称,而不是计算机名称)、get-process(管道是进程名称)和测试连接。这些都使用 Computername 和 ByPropertyName 的东西。最终结果是使用
-ComputerName (Get-Content Servers.txt)而不是Get-Content Servers.txt |运行它
标签: powershell