Safely converting string to bool in PowerShell

前端 未结 6 1367
孤城傲影
孤城傲影 2020-12-18 19:03

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

6条回答
  •  攒了一身酷
    2020-12-18 19:40

    just looked for this again and found my own answer - but as a comment so adding as an answer with a few corrections / other input values and also a pester test to verify it works as expected:

    Function ParseBool{
        [CmdletBinding()]
        param(
            [Parameter(Position=0)]
            [System.String]$inputVal
        )
        switch -regex ($inputVal.Trim())
        {
            "^(1|true|yes|on|enabled)$" { $true }
    
            default { $false }
        }
    }
    
    Describe "ParseBool Testing" {
        $testcases = @(
            @{ TestValue = '1'; Expected = $true },
            @{ TestValue = ' true'; Expected = $true },
            @{ TestValue = 'true '; Expected = $true },
            @{ TestValue = 'true'; Expected = $true },
            @{ TestValue = 'True'; Expected = $true },
            @{ TestValue = 'yes'; Expected = $true },
            @{ TestValue = 'Yes'; Expected = $true },
            @{ TestValue = 'on'; Expected = $true },
            @{ TestValue = 'On'; Expected = $true },
            @{ TestValue = 'enabled'; Expected = $true },
            @{ TestValue = 'Enabled'; Expected = $true },
    
            @{ TestValue = $null; Expected = $false },
            @{ TestValue = ''; Expected = $false },
            @{ TestValue = '0'; Expected = $false },
            @{ TestValue = ' false'; Expected = $false },
            @{ TestValue = 'false '; Expected = $false },
            @{ TestValue = 'false'; Expected = $false },
            @{ TestValue = 'False'; Expected = $false },
            @{ TestValue = 'no'; Expected = $false },
            @{ TestValue = 'No'; Expected = $false },
            @{ TestValue = 'off'; Expected = $false },
            @{ TestValue = 'Off'; Expected = $false },
            @{ TestValue = 'disabled'; Expected = $false },
            @{ TestValue = 'Disabled'; Expected = $false }
        )
    
    
        It 'input  parses as ' -TestCases $testCases {
            param ($TestValue, $Expected)
            ParseBool $TestValue | Should Be $Expected
        }
    }
    

提交回复
热议问题