gpt4 book ai didi

powershell - try catch 问题Powershell

转载 作者:行者123 更新时间:2023-12-02 23:46:55 26 4
gpt4 key购买 nike

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



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

*异常成功捕获

*文字“内线”,“外线”



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

*未捕获异常

*文字“内部捕获”未打印”

*获取以下错误消息
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

题:

我希望捕获第二个异常。我无法找出代码中的错误。

谢谢

朱加里

最佳答案

您正在将-ErrorAction Stop应用于Invoke-Expression,它执行得很好。要将错误操作指令应用于所调用的表达式,您需要将其附加到$cmd:

Invoke-Expression "$cmd -ErrorAction Stop"

或设置 $ErrorActionPreference = "Stop":
$eap = $ErrorActionPreference
$ErrorActionPreference = "Stop"
try {
Invoke-Expression $cmd
} catch {
Write-Host "Inside catch"
}
$ErrorActionPreference = $eap

后者是更可靠的方法,因为它没有对 $cmd进行假设。

关于powershell - try catch 问题Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18572949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com