这是简单的代码:
function getcomputer() {
if (($a.Length) -eq "1") {
if (-not(Test-Path "C:\users\ka1\documents\listofmachines$a.txt")) {
Write-Host "File C:\users\ka1\documents\listofmachines$a.txt not Found"
exit
}
$comps = gc "C:\users\ka1\documents\listofmachines$a.txt"
}
if (-not($a)) {
if (-not(Test-Path "C:\users\ka1\documents\listofmachines.txt")) {
Write-Host "File C:\users\ka1\documents\listofmachines.txt not Found"
exit
}
$comps = gc "C:\users\ka1\documents\listofmachines.txt"
}
return $comps
}
此getcomputer
函数在第一个PowerShell中调用:
$sccmexe ="C:\Program Files (x86)\SCCM Remote Control Toolset\CmRcViewer.exe"
$ScriptName = $MyInvocation.MyCommand.Name
Write-Host $ScriptName
$a = Read-Host -Prompt 'Please type the computername (or Enter for list)'
getcomputer $a
foreach ($computer in $computers) {
if ((Test-Connection -ComputerName $computer -Count 1 -Quiet) -eq $true) {
& $sccmexe $computer
} else {
Write-Host "$computer offline"
}
}
我期待做的事情似乎很简单,只需将管道$Comps
(我可以处理计算机)返回到主脚本。我应该保留$a
而不是将其更改为$comps
吗?
答案 0 :(得分:0)
PowerShell函数return成功输出流上的所有输出。管道从其上游cmdlet或进程读取成功输出流。您需要做的就是更改foreach
loop to a ForEach-Object
loop(将循环变量更改为$_
!)并使用管道将其连接到getcomputer
:
getcomputer $a | ForEach-Object {
if ((Test-Connection -ComputerName $_ -Count 1 -Quiet) -eq $true) {
...
} else {
...
}
}