如何在Powershell中处理失败的变量分配? [英] How to handle failed variable assignments in powershell?
问题描述
我正在尝试通过注册表项设置PowerShell变量。
I am trying to handle setting a PowerShell variable from a registry key.
所以我使用 try {} catch {}
来消除最终的错误,以防密钥不起作用。 t存在。但是,我仍然在控制台上收到错误输出。
So I use a try{} catch {}
to get rid of eventual errors in case the key doesn't exists. However, I still get the error output on console.
$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
仅捕获终止错误。
What your Get-ItemProperty
call emits is a non-terminating error, whereas try
/ catch
only catches terminating errors.
- 非终止错误比终止错误更为常见。
使用< a href = https://docs.microsoft.com/zh-cn/powershell/module/microsoft.powershell.core/about/about_CommonParameters#erroraction rel = nofollow noreferrer>常用参数 -ErrorAction Stop
,将cmdlet生成的(第一个)非终止错误提升为尝试
的终止错误/ catch
句柄。
Use common parameter -ErrorAction Stop
to promote (the first) non-terminating error generated by a cmdlet to a terminating one that try
/ catch
handles.
通常,通过设置 preference变量可以达到相同的效果。
$ ErrorActionPreference ='Stop'
,但请注意,这样做对调用 external无效程序以及在模块中实现的功能。
You can generally achieve the same effect by setting preference variable
$ErrorActionPreference = 'Stop'
beforehand, but note that doing so has no effect on calls to external programs and on functions implemented in modules.
另请参见:
-
about_Try_Catch_Finally
帮助主题。
The
about_Try_Catch_Finally
help topic.
乐趣的描述严重错误类型,以指导命令作者何时发出终止错误和非终止错误的方式:此答案。
A description of the fundamental error types in the context of guidance for command authors on when to emit a terminating vs. a non-terminating error: this answer.
PowerShell异常复杂的错误处理的全面概述:此GitHub文档问题。
A comprehensive overview of PowerShell's surprisingly complex error handling: this GitHub docs issue.
这篇关于如何在Powershell中处理失败的变量分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!