我正在编写一个故障排除脚本来确定我们域中的哪些 IP 地址可以被 WMI 访问,哪些不能。该脚本将读取输入参数列表(大约 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
}
编辑
@超级安东尼
我将我的代码更新为以下
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 错误。
再次感谢!