How to get the error code when there is error in powershell?

前端 未结 2 2133
伪装坚强ぢ
伪装坚强ぢ 2021-02-12 19:16

My snippet is something like this:

$msg=Remove-Item -Recurse -Force C:\\users\\bkp  2>&1
if ($LASTEXITCODE -eq 1)
{
  \"Encountered error during Deleting          


        
2条回答
  •  甜味超标
    2021-02-12 19:24

    $LASTEXITCODE is strictly for command line programs to return their status. Cmdlets that are built into PS, such as Remove-item return their errors in up to 3 ways. For warnings, they write messages (or other .NET objects) to the "warning stream". In PSv3 there is a straightforward way to redirect that stream to a file: cmdlet blah blah blah 3>warning.out. The second is via the error stream. That stream can be redirected as well ... 2>error.out, or more typically errors are caught with try/catch or trap, or written to a variable with the -ErrorVariable parameter (see help about_commonparameters). The third way is for errors to be "thrown". Unless caught (try/catch or trap), a thrown error will cause the script to terminate. Thrown errors generally are subclasses of the .NET class system.Management.Automation.ErrorRecord. An ErrorRecord provides a lot more information about an error than a return code.

    If remove-item fails due to a file not found error, it writes a System.Management.Automation.ItemNotFoundException to the error stream. Using a try/catch you can filter for that specific error or other specific errors from remove-item. If you are just typing in PS commands from the command line you can enter $error[0]|select-object * to get a lot of info on the last error.


    You could do this:

    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
    }
    

提交回复
热议问题