gpt4 book ai didi

PowerShell Try/Catch with If 语句

转载 作者:行者123 更新时间:2023-12-01 11:19:22 25 4
gpt4 key购买 nike

问题/细节

我在 PowerShell 中工作,并试图弄清楚自定义 Try Catch 语句的工作原理。我当前的主要问题涉及混合 Try/Catch 和 If 语句。所以我想要实现的想法是这样的:

try {
if (!$someVariable.Text) { throw new exception 0 }
elseif ($someVariable.Text -lt 11) { throw new exception 1 }
elseif (!($someVariable.Text -match '[a-zA-Z\s]')) { throw new exception 2}
}
catch 0 {
[System.Windows.Forms.MessageBox]::Show("Custom Error Message 1")
}
catch 1 {
[System.Windows.Forms.MessageBox]::Show("Custom Error Message 2")
}
catch 2 {
[System.Windows.Forms.MessageBox]::Show("Custom Error Message 3")
}

现在我知道上面的代码与实际代码相比是非常不准确的,但我想直观地展示我的想法和尝试实现的目标。

问题

有谁知道如何使用 PowerShell 创建自定义错误消息,这可以帮助我实现接近上述想法的目标并稍微解释一下您的答案?提前谢谢你

到目前为止,下面的链接是我发现的最接近我正在努力实现的目标:

PowerShell Try, Catch, custom terminating error message

最佳答案

您抛出的错误存储在 $_.Exception.Message

$a = 1
try{
If($a -eq 1){
throw "1"
}
}catch{
if ($_.Exception.Message -eq 1){
"Error 1"
}else{
$_.Exception.Message
}
}

关于PowerShell Try/Catch with If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45762639/

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