在powershell中尝试方法
所以我想在下面的 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]
So I want to build a try method into my powershell script below. If I am denied access to a server, I want it to skip that server. Please help..
[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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Try/catch 功能内置于 PowerShell 2.0 中,例如:
只需将脚本包装在类似的 try/catch 中即可。请注意,您可以通过将 catch 块留空
catch { }
来完全忽略该错误,但如果您的 $DebugPreference 设置为“Continue”,我建议至少吐出错误信息。Try/catch functionality is built-into PowerShell 2.0 e.g.:
Just wrap you script in a similar try/catch. Note you could totally ignore the error by leaving the catch block empty
catch { }
but I would recommend at least spitting out the error info if your $DebugPreference is set to 'Continue'.您可以使用 ErrorAction 参数简单地抑制错误:
Get-WmiObject Win32_LogicalMemoryConfiguration -Computer $Computers -ErrorAction SilentlyContinue | ...
You can simply suppress errors with the ErrorAction parameter:
Get-WmiObject Win32_LogicalMemoryConfiguration -Computer $Computers -ErrorAction SilentlyContinue | ...
您可以使用 trap 来复制 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 例如。
You can use trap to replicate Try/Catch, see http://huddledmasses.org/trap-exception-in-powershell/ or http://weblogs.asp.net/adweigert/archive/2007/10/10/powershell-try-catch-finally-comes-to-life.aspx for examples.
使用过滤功能? 就像本教程所解释的。
他将计算机列表传递给他的管道 - 首先它尝试对每个管道进行 ping 操作,然后仅传递响应下一个命令(重新启动)的管道。您可以根据您想要的任何实际功能对其进行自定义。
Use a filter function? Like this tutorial explains.
He passes a list of computers to his pipeline - first it tries to ping each one, and then only passes the ones that respond to the next command (reboot). You could customize this for whatever actual functionality you wanted.