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

前端 未结 2 2140
伪装坚强ぢ
伪装坚强ぢ 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
    }
    
    0 讨论(0)
  • 2021-02-12 19:29

    You can use the $? automatic variable to determine the result of the last command. If you need access to the actual error, you can use the $Error automatic variable. The first item in the array is the last error thrown:

    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
    }
    
    0 讨论(0)
提交回复
热议问题