问题描述
我有一个简单的循环,它得到服务器列表中的所有序列号;
开始
foreach($ computer in $ computers)
{
try
{
Get-WmiObject -computer $ computer -Class Win32_OperatingSystem | Select Serial *
}
catch
{
写入主机无效的服务器
}
}
END
但是,输出看起来很丑,出现以下错误以及几个服务器的正确输出
Get-WmiObject:RPC服务器不可用
Get-WmiObject:访问被拒绝等(不是 Try / Catch 强>循环以消除那些?)
奇怪的是,输出说无效的服务器,所以错误之间的区别和Try / Catch循环?
我在这里做错了什么?请问如果有任何问题。
为了使上述代码抛出异常,您可以添加 -ErrorAction停止
到您的 Get-WmiObject
行,如下所示:
code> Get-WmiObject -computer $ computer - 类Win32_OperatingSystem -ErrorAction Stop |选择Serial *
看到Keith Hill的这篇文章:。 p>
I got a simple loop which gets all the serial Numbers in the Server List;
Start
foreach ($computer in $computers)
{
try
{
Get-WmiObject -computer $computer -Class Win32_OperatingSystem|Select Serial*
}
catch
{
Write-Host "Invalid Server"
}
}
END
But, the output looks all ugly with following errors as well as the correct outputs for few servers.
Get-WmiObject : The RPC server is unavailableGet-WmiObject : Access Denied etc (Isnt it the purpose of Try/Catch loop to eliminate those?)
Strangely soemtimes the output says "Invalid Server" too , so what exactly is the difference between errors and what are the limitations of Try/Catch loops?
What am i doing wrong here? Please if any questions.
To make the above code throw an exception, you can add -ErrorAction Stop
to your Get-WmiObject
line, like this:
Get-WmiObject -computer $computer -Class Win32_OperatingSystem -ErrorAction Stop | Select Serial*
See this article by Keith Hill: distinction between "terminating" and "non-terminating" errors.
这篇关于为什么错误通过TRY / CATCH循环在Powershell中滑倒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!