2016-08-20 32 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

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