Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

boolean - Safely converting string to bool in PowerShell

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

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

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.

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could use a try / catch block:

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

Gives:

> $result
False

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...