接受来自pipe道Powershell函数的值

我想创build一个脚本,告诉用户是否在多个远程机器上启用PSRemoting。 这是我到目前为止:

function Test-PSRemoting { Param( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] [string[]] $ComputerName, [string] $Credential) $file = Read-Host "Enter file location for all error details: " try { $result = Invoke-Command -ComputerName $ComputerName -Credential $Credential { 1 } -ErrorAction SilentlyContinue -ErrorVariable Problem If ($Problem){ $result = 0} } catch { $result = 0} If ($result -eq 1){ write-host "PSRemoting is enabled on: " $ComputerName } else { write-host "PSRemoting is not enabled/working on: " $ComputerName $Problem | Out-File $file -Append} } 

如果我只指定一台电脑,该function完美的工作:

 Test-PSRemoting -ComputerName Server1 - Credentials Admin 

但是,如果指定多台计算机,则无法使用此function:

 Test-PSRemoting -ComputerName Server1, Server2 - Credentials Admin Server1, Server2 | Test-PSRemoting -Credentials Admin 

在这种情况下,我会使用Process {}块(也会回答你为什么只检查Server2的意见)。

 function test-ps { param( [Parameter(ValueFromPipeline=$true)] [string[]] $CN ) process{ Write-Host $CN "h" } } 'test1','test2' | test-ps 

http://ss64.com/ps/syntax-function-input.html

请尝试下面的注释以下注释要点。

 function Test-PSRemoting { [CmdletBinding()] param ( [Parameter(Mandatory = $True, ValueFromPipeline = $True)] [string[]]$ComputerName, [Parameter(Mandatory = $False)] [System.Management.Automation.PSCredential]$Credential = (Get-Credential), [Parameter(Mandatory = $True)] [String]$OutFile ) process { # Pass computer name along the pipeline to allow for more then one. $ComputerName | % ` { $pcName = $_; $problem = $Null; try { $result = Invoke-Command -ComputerName $pcName -Credential $Credential { 1 } -ErrorAction SilentlyContinue -ErrorVariable problem; if ($problem -eq $Null -and $result -eq 1) { # Use Write-Verbose instead. Test-* commands are meant to return true/false. # But additional status can be viewed by adding the -Verbose parameter to Test-PSRemoting. ie Test-PSRemoting -Verbose Write-Verbose "PSRemoting is enabled on: $pcName"; return $True; } else { Write-Verbose "PSRemoting is not enabled/working on: $pcName"; $problem | Out-File $OutFile -Append; return $False; } } catch { return $False } } } } 

要点是:

  • 使用$ComputerName | 通过处理您指定的每个计算机名称的条件逻辑来允许Test-PSRemoting -ComputerName Server1,Server2使用情况。 Invoke-Command自然会处理多个计算机名称,但是您的if语句不会。
  • $file移动到$OutFile参数而不是Read-Host,并将其标记为强制参数以强制input。 在一个process { }留下Read-Host块将意味着如果Server1,Server2 | Test-PSRemoting被多次请求文件path Server1,Server2 | Test-PSRemoting 。 还具有能够作为参数而不是每次手动input的优点。
  • 将详细输出移至Write-Verbose而不是Write-Host 。 Test- *命令应该返回True / False而不是string。 使用-Verbose查看详细的输出。 此外,您可以更改Write-Verbose "PSRemoting is not enabled/working on: $pcName"; 改为Write-Warning