powershell出现错误时如何获取错误代码? [英] How to get the error code when there is error in powershell?

查看:67
本文介绍了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.我如何捕获为标志?

The folder C:\users\bkp does not exist. Even though $msg gives me the error message $LASTEXITCODE is still 0. How do I capture as a flag?

推荐答案

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

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
}

这篇关于powershell出现错误时如何获取错误代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆