所以我想在下面的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]
答案 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)
您可以使用陷阱来复制Try / Catch,有关示例,请参阅http://huddledmasses.org/trap-exception-in-powershell/或http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx。
答案 3 :(得分:0)
使用过滤功能? Like this tutorial explains.
他将计算机列表传递给他的管道 - 首先它尝试对每个计算机执行ping操作,然后只传递响应下一个命令的那些计算机(重新启动)。您可以根据自己想要的任何实际功能对其进行自定义。