2016-08-20 34 views
0

下面是简单的代码:试图从一个PowerShell功能通过管道

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

综观目前还不清楚的代码要如何使用它,为什么你可以只是'返回$ comp'。 {{}括号也是不平衡的,缩进是误导。如果您将代码减少到相关最小值([MCVE](https://stackoverflow.com/help/mcve)),将会很有帮助。 – wOxxOm

+0

我很想使用return $ comp,但它似乎不会返回管道。我相信我没有得到什么。这段代码抓住了我正在使用的listofmachinesx.txt。如果listofmachinesa.txt存在,它会加载所有的机器和我编码的东西。 –

回答

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 { 
    ... 
    } 
} 
+0

这真是太棒了。正是我想要的。 –