默默处理PowerShell中的错误

时间:2013-09-03 19:32:08

标签: powershell error-handling

我正在编写一个故障排除脚本,以确定WMI可以访问我们域中的哪些IP地址,哪些不是。该脚本将读取输入参数列表(约18,000行),并将IP地址和用户名输出到文件

IP address, Username

问题是,当抛出WMI错误时,它会写入文件

IP address, Get-WmiObject : The RPC server is unavailable. .....numerous lines of error

我想这样做,当它抛出WMI错误时,它会写下面的

IP address, "WMI ERROR"

以下是经过修改的参考代码

#script_modified.ps1

$abc = $args
$startInfo = $NULL
$process = $NULL
$standardOut = $NULL


<#Previously created password file in C:\Script\cred.txt, read-host -assecurestring | convertfrom-securestring | out-file C:\Script\cred.txt#>
$password = get-content C:\Script\cred.txt | convertto-securestring

$a = Get-Content "C:\Script\test_input.txt"

foreach ($b in $a){

    $startInfo = New-Object System.Diagnostics.ProcessStartInfo
    $startInfo.FileName = "powershell.exe"
    $startInfo.Arguments = "C:\script\script2.ps1 " + $b

    $startInfo.RedirectStandardOutput = $true
    $startInfo.UseShellExecute = $false
    $startInfo.CreateNoWindow = $false
    $startInfo.Username = "service.infosec"
    $startInfo.Domain = "Central"
    $startInfo.Password = $password 

    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $startInfo
    $process.Start() | Out-Null
    $standardOut = $process.StandardOutput.ReadToEnd()
    $process.WaitForExit()

    # $standardOut should contain the results of "C:\script\script2.ps1"

   Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$standardOut
}

修改

@Hyper Anthony

我将代码更新为以下

try{
    $process.StartInfo = $startInfo
}
catch{
    $message = "WMI ERROR"
}
finally{
    $process.WaitForExit()
    Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$message
}

我得到以下错误:

Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\script\script_modified.ps1:36 char:29
+         $process.WaitForExit <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

如何解决?

编辑:

以下是更新的代码:

foreach ($b in $a){

    $startInfo = New-Object System.Diagnostics.ProcessStartInfo
    $startInfo.FileName = "powershell.exe"

    ...More Code...

    $process = New-Object System.Diagnostics.Process
    $process.StartInfo = $startInfo

    try{
        $process.Start() | Out-Null
        $standardOut = $process.StandardOutput.ReadToEnd()
    }
    catch{
        $standardOut = "WMI ERROR"
    }
    finally{
        $process.WaitForExit()
        Add-Content C:\script\list_of_computers_in_DOMAIN.log $b","$standardOut
    }

}

不再有任何错误输出到控制台,但输出文件不是我想要的。

当出现WMI错误时,我希望写下以下行

  

'sender-ip = 10.10.10.10',WMI错误

但是,编写以下内容

  

'sender-ip = 10.10.10.10',Get-WmiObject:RPC服务器不可用。   (来自HRESULT的异常:0x800706BA)......多行错误

可能会打印

或任何其他错误而不是WMI错误。

再次感谢!

0 个答案:

没有答案