2017-08-25 98 views
0

我想輸入列表中的每臺計算機並從中刪除一個軟件。Enter-PSSession不返回變量

當我嘗試代碼(不使用foreach)時,代碼工作正常。但是當我嘗試循環它時,它根本不起作用。

哪裏有「做點什麼」,它什麼都不做。舉例來說,我試圖做的:

$product = Get-WmiObject -Class Win32_Product | Where-Object {$_.name -like "7-zip*"} 

,並在下一行,在屏幕上打印的$product變量。但它總是空的。

當我手動輸入pssession並運行此命令時,它返回給我一些東西。

我在做什麼錯在這裏?我已經浪費了幾個小時試圖弄清楚這一點,但沒有運氣:(

foreach ($computer in $computers){ 

    if(Test-Connection "$computer" -Count 1 -ErrorAction SilentlyContinue){ 

     Enter-PSSession -ComputerName $computer 

     "do something" 

     Exit-PSSession 

    }else{ 

     Write-Warning "computer is offline." 

    } 
} 
+2

https://stackoverflow.com/questions/3705321/enter-pssession -s-not-working-in-my-powershell-script-Enter-PSSession不能用於腳本中,僅用於交互式使用 – Raziel

回答

1

使用調用命令 例:

$ReturnValue = Invoke-Command -ComputerName $ComputerName -ScriptBlock{ 
    #DoSomethingHere 
} 
Write-host $Returnvalue #Will print the output of the scriptblock 
+0

啊,這太棒了!它現在可以工作!非常感謝! – mergulhao21