gpt4 book ai didi

powershell - 如何在powershell中处理失败的变量分配?

转载 作者:行者123 更新时间:2023-12-03 07:56:16 28 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Try/catch does not seem to have an effect

(7 个回答)


2年前关闭。




我正在尝试从注册表项设置 PowerShell 变量。

所以我使用 try{} catch {}在 key 不存在的情况下摆脱最终的错误。但是,我仍然在控制台上得到错误输出。

$ZZ_ConVTL = try { (Get-ItemProperty -path "HKCU:\Console" -name VirtualTerminalLevel).VirtualTerminalLevel } catch { "N/A" }

...

# Output:
Get-ItemProperty : Property VirtualTerminalLevel does not exist at path HKEY_CURRENT_USER\Console.
At C:\Users\Administrator\Documents\xxxx\xxxx.ps1:181 char:32
+ ... = try { (Get-ItemProperty -path "HKCU:\Console" -name VirtualTermi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (VirtualTerminalLevel:String) [Get-ItemProperty], PSArgumentException
+ FullyQualifiedErrorId : System.Management.Automation.PSArgumentException,Microsoft.PowerShell.Commands.GetItemPropertyCommand


如何处理并避免此错误出现在控制台中?

最佳答案

你的Get-ItemProperty调用发出的是非终止错误,而 try/catch只捕获终止错误。

  • 非终止错误比终止错误更常见。

  • 使用common parameter -ErrorAction Stop 将 cmdlet 生成的(第一个)非终止错误提升为 try 的终止错误/ catch handle 。

    一般可以通过设置 来达到同样的效果偏好变量
    $ErrorActionPreference = 'Stop' 事先,但请注意,这样做对外部程序的调用和模块中实现的函数没有影响。

    也可以看看:
  • about_Try_Catch_Finally 帮助主题。
  • 的描述基本错误类型 在命令作者关于何时发出终止与非终止错误的指导的上下文中:this answer .
  • 一个 综合概览 PowerShell 异常复杂的错误处理:this GitHub docs issue .
  • 关于powershell - 如何在powershell中处理失败的变量分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64776548/

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