安全字符串转换在PowerShell中为bool [英] Safely converting string to bool in Powershell

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

问题描述

我想我的PowerShell脚本的参数转换成一个布尔值。此行

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

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

只要罚款,我用有效的值,如真或假,但是,当一个无效的值,如喇嘛或通过后,将返回错误的作品。我需要的东西类似的TryParse,这将只是其值设置为false,如果输入的值无效,并返回一个布尔值,指示转换成功或失败。
为了记录在案,我试过[布尔] ::的TryParse和[布尔] ::的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中为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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