尝试使用powershell中的方法

时间:2010-05-12 16:50:12

标签: powershell wmi

所以我想在下面的powershell脚本中构建一个try方法。如果我被拒绝访问服务器,我希望它跳过该服务器。请帮忙..

[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 个答案:

答案 0 :(得分: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设置为“Continue”,我建议至少吐出错误信息。

答案 1 :(得分:2)

您可以使用ErrorAction参数简单地抑制错误:

Get-WmiObject Win32_LogicalMemoryConfiguration -Computer $ Computers -ErrorAction SilentlyContinue | ...

答案 2 :(得分:0)

答案 3 :(得分:0)

使用过滤功能? Like this tutorial explains.

他将计算机列表传递给他的管道 - 首先它尝试对每个计算机执行ping操作,然后只传递响应下一个命令的那些计算机(重新启动)。您可以根据自己想要的任何实际功能对其进行自定义。