在 PowerShell 中安全地将字符串转换为布尔值 [英] Safely converting string to bool in PowerShell

查看:52
本文介绍了在 PowerShell 中安全地将字符串转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 PowerShell 脚本的参数转换为布尔值.这一行

I'm trying to convert an argument of my PowerShell script to a boolean value. This line

[System.Convert]::ToBoolean($a)

只要我使用true"或false"等有效值就可以正常工作,但是当传递bla"或"等无效值时,会返回错误.我需要类似于 TryParse 的东西,如果输入值无效,它只会将值设置为 false,并返回一个指示转换成功或失败的布尔值.作为记录,我尝试了 [boolean]::TryParse 和 [bool]::TryParse,PowerShell 似乎无法识别它.

works fine as long as I use valid values such as "true" or "false", but when an invalid value, such as "bla" or "" is passed, an error is returned. I need something akin to TryParse, that would just set the value to false if the input value is invalid and return a boolean indicating conversion success or failure. For the record, I tried [boolean]::TryParse and [bool]::TryParse, PowerShell doesn't seem to recognize it.

现在我不得不通过两个额外的 if 语句笨拙地处理这个问题.

Right now I'm having to clumsily handle this by having two extra if statements.

令我惊讶的是,到目前为止我发现的所有操作指南和博客文章都没有处理无效值.是我遗漏了什么,还是 PowerShell 的孩子们太酷了,无法进行输入验证?

What surprised me that none of the how-to's and blog posts I've found so far deal with invalid values. Am I missing something or are the PowerShell kids simply too cool for input validation?

推荐答案

你可以使用 try/catch 块:

You could use a try / catch block:

$a = "bla"
try {
  $result = [System.Convert]::ToBoolean($a) 
} catch [FormatException] {
  $result = $false
}

给予:

> $result
False

这篇关于在 PowerShell 中安全地将字符串转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆