MrRobot
MrRobot

Reputation: 31

Convert Boolean Value to String

I am trying to convert my boolean values in PowerShell to the following:

Here is my relevant code for this

$SecMasSQLRes | ForEach-Object {
    if ($SecMasSQLRes.CusipPercent -lt 25) {
        Write-Host CusipStatus = GREEN
    } else {
        Write-Host CusipStatus = RED
    }

    if ($SecMasSQLRes.ISINPercent -lt 10) {
        Write-Host IsinStatus = GREEN
    } else {
        Write-Host IsinStatus = RED
    }

    if ($SecMasSQLRes.SymbolPercent -lt 10) {
        Write-Host SymbolStatus = GREEN
    } else {
        Write-Host SymbolStatus = RED
    }
}

$CusipResults = $SecMasSQLRes.CusipPercent -lt 25
$IsinResults = $SecMasSQLRes.ISINPercent -lt 10
$SymbolResults = $SecMasSQLRes.SymbolPercent -lt 10

$CusipResults
$IsinResults
$SymbolResults

Upvotes: 3

Views: 11141

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200203

There are several ways how you could approach this:

  • Use an if/else statement as suggested by @PetSerAl:

    if (condition) {'GREEN'} else {'RED'}
    
  • Use a switch statement:

    switch (condition) { $true {'GREEN'} default {'RED'} }
    
  • Use a hashtable as suggested by @TessellatingHeckler:

    $light = @{$true = 'GREEN'; $false = 'RED'}
    $light[(condition)]
    
  • Use the boolean values (implicitly cast to integers) as index in an array as suggested by @Mathias R. Jessen:

    @('RED', 'GREEN')[(condition)]
    

Personally, I think the hashtable method is the cleanest approach, so I'd prefer that one:

$light = @{
    $true  = 'GREEN'
    $false = 'RED'
}

$SecMasSQLRes | ForEach-Object {
    Write-Host CusipStatus = $light[($_.CusipPercent -lt 25)]
    Write-Host IsinStatus = $light[($_.ISINPercent -lt 10)]
    Write-Host SymbolStatus = $light[($_.SymbolPercent -lt 10)]
}

Upvotes: 3

Related Questions