我正在尝试运行Powershell脚本并显示错误代码和错误消息(如果失败)。应该以这种格式向我输出结果:
"FAILED;ErrorCode;ErrorMessage;"
这是我的剧本:
param([String]$Cab_Type)
$output
if(!(Test-Connection -Cn 165.100.10.10 -BufferSize 16 -Count 1 -quiet))
{
$output = "FAILED; " + $LASTEXITCODE + ";" + $error[0] + ";"
}
else
{
$output = "PASSED"
}
Write-Host $Cab_Type
Write-Host "<ScriptResult_Start>"
Write-Host $output
Write-Host "<ScriptResult_End>"
我试图故意对我知道会失败的地址执行ping操作。 运行脚本时,它会向我返回错误消息,但不会返回错误代码。
$ LASTEXITCODE是否不返回脚本的错误代码?即使我的脚本有效,它是否仅返回0或1?有没有办法获取脚本的实际错误代码?
答案 0 :(得分:1)
也许这就是你所追求的?
# set up a hash with possible Ping status codes
$status = @{
11001 = 'Buffer Too Small'
11002 = 'Destination Net Unreachable'
11003 = 'Destination Host Unreachable'
11004 = 'Destination Protocol Unreachable'
11005 = 'Destination Port Unreachable'
11006 = 'No Resources'
11007 = 'Bad Option'
11008 = 'Hardware Error'
11009 = 'Packet Too Big'
11010 = 'Request Timed Out'
11011 = 'Bad Request'
11012 = 'Bad Route'
11013 = 'TimeToLive Expired Transit'
11014 = 'TimeToLive Expired Reassembly'
11015 = 'Parameter Problem'
11016 = 'Source Quench'
11017 = 'Option Too Big'
11018 = 'Bad Destination'
11032 = 'Negotiating IPSEC'
11050 = 'General Failure'
}
$server = '165.100.10.10'
$ping = (Get-WmiObject -Class Win32_PingStatus -Filter "Address='$server'").StatusCode
if (!$ping -or [int]$ping -ne 0) {
$err = if ( $status[[int]$ping]) { $status[[int]$ping] } else { "Unknown Failure" }
$output = "FAILED; $ping; $err"
}
else { $output = "PASSED" }
Write-Host $output
上面的示例输出:
FAILED; 11010; Request Timed Out
答案 1 :(得分:0)
有多种方法可以处理错误并进行验证。首先,我希望您将主要代码保留在try/catch
块下并捕获错误消息,以便您了解错误的确切含义。下面是对代码的修改。
param([String]$Cab_Type)
$output
try
{
if(!(Test-Connection -Cn 165.100.10.10 -BufferSize 16 -Count 1 -quiet))
{
$output = "FAILED; " + $LASTEXITCODE + ";" + $error[0] + ";"
}
else
{
$output = "PASSED"
}
Write-Host $Cab_Type
Write-Host "<ScriptResult_Start>"
Write-Host $output
Write-Host "<ScriptResult_End>"
}
catch
{
$_.Exception.Message
}
还要经历大约1个。TRY CATCH FINALLY in PS
除此之外,您可以使用$Error
变量来了解所有错误。
浏览2。About $Error variable and how to use it effectively
您还需要了解3。Powershell Exceptions and Everything you ever wanted to know
希望它会有所帮助,并为您提供指导。