如何在PowerShell中出现错误时获取错误代码?

时间:2013-07-04 02:42:42

标签: powershell

我的代码片段是这样的:

$msg=Remove-Item -Recurse -Force C:\users\bkp  2>&1
if ($LASTEXITCODE -eq 1)
{
  "Encountered error during Deleting the Folder. Error Message is $msg. Please check." >> $LogFile
  exit
 }

文件夹C:\ users \ bkp不存在。即使$ msg给我错误消息$ LASTEXITCODE仍为0.我如何捕获为标志?

2 个答案:

答案 0 :(得分:18)

您可以使用$? automatic variable来确定最后一个命令的结果。如果您需要访问实际错误,可以使用$Error自动变量。数组中的第一项是抛出的最后一个错误:

Remove-Item -Recurse -Force C:\users\bkp 2>&1
if( -not $? )
{
    $msg = $Error[0].Exception.Message
    "Encountered error during Deleting the Folder. Error Message is $msg. Please check." >> $LogFile
    exit
}

答案 1 :(得分:9)

$ LASTEXITCODE严格用于命令行程序以返回其状态。内置到PS中的Cmdlet,例如Remove-item,最多可以3种方式返回错误。对于警告,他们将消息(或其他.NET对象)写入“警告流”。在PSv3中,有一种直接的方法可以将该流重定向到文件:cmdlet blah blah blah 3>warning.out。第二个是通过错误流。该流也可以重定向... 2>error.out,或者更常见的错误是通过try / catch或trap捕获,或者使用-ErrorVariable参数写入变量(请参阅help about_commonparameters)。第三种方式是“抛出”错误。除非被捕获(try / catch或trap),否则抛出的错误将导致脚本终止。抛出的错误通常是.NET类system.Management.Automation.ErrorRecord的子类。 ErrorRecord提供了有关错误的更多信息,而不是返回代码。

如果由于找不到文件错误导致remove-item失败,则会将System.Management.Automation.ItemNotFoundException写入错误流。使用try / catch,您可以从remove-item过滤该特定错误或其他特定错误。如果您只是从命令行输入PS命令,则可以输入$error[0]|select-object *以获取有关上一个错误的大量信息。


你可以这样做:

try {
  Remove-Item -Recurse -Force C:\users\bkp  2>&1
} catch {
  # oops remove-item failed. Write warning then quit 
  # replace the following with what you want to do
  write-warning "Remove-item encounter error: $_"
  return # script failed
}