2010-05-12 39 views
0

所以我想在下面的PowerShell腳本中構建一個try方法。如果我拒絕訪問服務器,我希望它跳過該服務器。請幫助..在PowerShell中嘗試方法

[code]$Computers = "server1", "server2" 

Get-WmiObject Win32_LogicalMemoryConfiguration -Computer $Computers | Select-Object ` 
@{n='Server';e={ $_.__SERVER }}, ` 
@{n='Physical Memory';e={ "$('{0:N2}' -f ($_.TotalPhysicalMemory/1024))mb" }}, ` 
@{n='Virtual Memory';e={ "$('{0:N2}' -f ($_.TotalPageFileSpace/1024))mb" }} | ` 
Export-CSV "output.csv"[/code] 

回答

4

的try/catch功能被內置到PowerShell 2.0中例如爲:

PS> try {$i = 0; 1/$i } catch { Write-Debug $_.Exception.Message }; 'moving on' 
Attempted to divide by zero. 
moving on 

只是包裝你在一個類似的try/catch腳本。請注意,您可以通過將catch塊留空catch { }完全忽略錯誤,但如果$ DebugPreference設置爲「繼續」,我會推薦至少吐出錯誤信息。

2

你可以簡單地抑制與ErrorAction參數錯誤:

GET-WmiObject可以Win32_LogicalMemoryConfiguration - 電腦$計算機-ErrorAction SilentlyContinue | ...

+1

只要有一點限定該語句 - 您可以使用ErrorAction參數來抑制「非終止」錯誤。 :-) – 2010-05-15 18:26:31

+0

的確,感謝Keith :)(Wmi的「拒絕訪問」是一個「非終止」錯誤) – 2010-05-15 22:12:00

0

使用過濾器功能? Like this tutorial explains.

他將計算機列表傳遞給他的管道 - 首先嚐試ping每個計算機,然後只傳遞響應下一個命令(重新啓動)的計算機。你可以自定義這個你想要的任何實際功能。