【问题标题】:How to handle failed variable assignments in powershell? [duplicate]如何在powershell中处理失败的变量分配? [复制]
【发布时间】:2020-04-24 21:35:02
【问题描述】:

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

所以我使用try{} catch {} 来消除最终的错误,以防密钥不存在。但是,我仍然在控制台上得到错误输出。

$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

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

【问题讨论】:

    标签: powershell error-handling


    【解决方案1】:

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

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

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

    您通常可以通过预先设置 preference 变量
    $ErrorActionPreference = 'Stop' 来达到相同的效果,但请注意,这样做不会影响对 的调用外部程序和在模块中实现的功能。


    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 2012-10-17
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多