Foreach尝试抓住

时间:2017-04-10 04:13:36

标签: powershell

我有一个包含计算机列表的文件,我需要遍历该列表并报告是否有空。

ALTER TABLE test ALTER COLUMN col TYPE keycount USING (col[1], col[2]::INTEGER)::keycount;

现在它可以正常工作,但我想抓住错误消息并将其更改为乱七八糟的计算机名称是免费的。

目前还在回归

quser : No User exists for *
At line:5 char:5
+     quser /server:$computer
+     ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (No User exists for *:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

对于免费的电脑。

我可以通过对我知道免费的计算机运行$list = get-content "pathtofile.txt" foreach ($computer in $list) { try { quser /server:$computer } catch [System.Management.Automation.RemoteException] { Write-Host "$computer is free" } } 命令然后运行System.Management.Automation.RemoteException来获取quser

writeErrorStream      : True
PSMessageDetails      : 
Exception             : System.Management.Automation.RemoteException: No User exists for *
TargetObject          : No User exists for *
CategoryInfo          : NotSpecified: (No User exists for *:String) [], RemoteException
FullyQualifiedErrorId : NativeCommandError
ErrorDetails          : 
InvocationInfo        : System.Management.Automation.InvocationInfo
ScriptStackTrace      : at , : line 1
PipelineIterationInfo : {0, 0}

这给了我异常代码。

现在我看了Foreach error handling in Powershell,它显示我的代码应该是正确的,所以不确定为什么捕获不起作用。

2 个答案:

答案 0 :(得分:4)

 $time = '09:15 PM';
 $s=Carbon::parse($time);
 echo $military_time =$s->format('G:i');

答案 1 :(得分:2)

我通常这样做:

$list = get-content "pathtofile.txt"

foreach ($computer in $list)
{
    try 
{
    quser /server:$computer
}
catch
{
    if ($Error.Exception -eq "System.Management.Automation.RemoteException: No User exists for *")
    {
        Write-Host "$computer is free"
    }
    else
    {
        throw $error
    }
}

}