Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
尝试捕获问题powershell #_Powershell - Fatal编程技术网

尝试捕获问题powershell #

尝试捕获问题powershell #,powershell,Powershell,第一次使用$cmd=“vgc monitors.exe”调用Test()(系统中不存在此exe) *成功捕获异常 *打印文本“内侧锁扣”“外侧锁扣” # 使用$cmd=“Get Content”C:\Users\Administrator\Desktop\PS\lib\11.txt”“第二次调用Test()(指定路径中不存在11.txt) *未捕获异常 *文本“内部捕捉”未打印 *获取以下错误消息 function Test($cmd) { Try {

第一次使用$cmd=“vgc monitors.exe”调用Test()(系统中不存在此exe)

*成功捕获异常

*打印文本“内侧锁扣”“外侧锁扣”

# 使用
$cmd=“Get Content”C:\Users\Administrator\Desktop\PS\lib\11.txt”“第二次调用Test()
(指定路径中不存在11.txt)

*未捕获异常

*文本“内部捕捉”未打印

*获取以下错误消息

function Test($cmd)
{
          Try
         {
                  Invoke-Expression $cmd -ErrorAction Stop
         }
         Catch
         {
                  Write-Host "Inside catch"
         }

         Write-Host "Outside catch"
}

$cmd = "vgc-monitors.exe"  #Invalid EXE
Test $cmd

$cmd = "Get-Content `"C:\Users\Administrator\Desktop\PS\lib\11.txt`""
Test $cmd
Get Content:找不到路径“C:\Users\Administrator\Desktop\PS\lib\11.txt”,因为它不存在。
第1行字符:12

+获取内容您正在将
-ErrorAction Stop
应用于
调用表达式
,该表达式执行得很好。要使error-action指令应用于调用的表达式,您需要将其附加到
$cmd

Get-Content : Cannot find path 'C:\Users\Administrator\Desktop\PS\lib\11.txt' because it does not exist.
At line:1 char:12
+ Get-Content <<<<  "C:\Users\Administrator\Desktop\PS\lib\11.txt"
    + CategoryInfo          : ObjectNotFound: (C:\Users\Admini...p\PS\lib\11.txt:String) [Get-Content], ItemNotFoundEx
   ception
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
或设置
$ErrorActionPreference=“Stop”


后者是更稳健的方法,因为它不会假设
$cmd

如果
$cmd
恰好是一个exe?或者出于某种原因,他们决定以
?@KeithHill结束命令,那么他就必须坚持我建议的第二个选项。我认为这更可取。:-)
Invoke-Expression "$cmd -ErrorAction Stop"
$eap = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try {
  Invoke-Expression $cmd
} catch {
  Write-Host "Inside catch"
}
$ErrorActionPreference = $eap