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

前端 未结 2 2135
伪装坚强ぢ
伪装坚强ぢ 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: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
    }
    

提交回复
热议问题