在powershell中尝试方法

发布于 2024-08-31 22:45:58 字数 454 浏览 4 评论 0原文

所以我想在下面的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

烙印 2024-09-07 22:45:58

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”,我建议至少吐出错误信息。

Try/catch functionality is built-into PowerShell 2.0 e.g.:

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

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'.

巷子口的你 2024-09-07 22:45:58

您可以使用 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 | ...

绝不放开 2024-09-07 22:45:58

使用过滤功能? 就像本教程所解释的。

他将计算机列表传递给他的管道 - 首先它尝试对每个管道进行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文