Programming Fundamentals/Conditions/PowerShell

From Wikiversity
Jump to navigation Jump to search

conditions.ps1[edit]

# This program asks the user for a Fahrenheit temperature, 
# converts the given temperature to Celsius,
# and displays the results.
#
# References:
#     https://www.mathsisfun.com/temperature-conversion.html
#     https://en.wikiversity.org/wiki/PowerShell/Conditions

function Get-Choice()
{
    Write-Host "Enter C to convert to Celsius or F to convert to Fahrenheit:"
    $choice = Read-Host
    return $choice
}

function If-Else()
{
    $choice = Get-Choice
    if($choice -eq 'C' -or $choice -eq 'c')
    {
        Process-Celsius
    }
    elseif($choice -eq 'F' -or $choice -eq 'f')
    {
        Process-Fahrenheit
    }
    else 
    {
        Write-Host 'You must enter C to convert to Celsius or F to convert to Fahrenheit.'
    }
}

function Switch-Case()
{
    $choice = Get-Choice
    switch ($choice)
    {
        C { Process-Celsius }
        F { Process-Fahrenheit }
        default { Write-Host 'You must enter C to convert to Celsius or F to convert to Fahrenheit.' }
    }
}
function Process-Celsius()
{
    $temperature = Get-Temperature "Fahrenheit"
    $result = Calculate-Celsius $temperature
    Display-Result $temperature "Fahrenheit" $result "Celsius"
}

function Process-Fahrenheit()
{
    $temperature = Get-Temperature "Celsius"
    $result = Calculate-Fahrenheit $temperature
    Display-Result $temperature "Celsius" $result "Fahrenheit"
}

function Get-Temperature($scale)
{
    Write-Host "Enter $scale temperature:"
    $temperature = Read-Host
    return $temperature
}

function Calculate-Celsius($fahrenheit)
{
    $celsius = ([double]$fahrenheit - 32) * 5 / 9
    return $celsius
}

function Calculate-Fahrenheit($celsius)
{
    $fahrenheit = [double]$celsius * 9 / 5 + 32
    return $fahrenheit
}

function Display-Result($temperature, $from, $result, $to)
{
    Write-Host $($temperature + '° ' + $from + ' is ' + $result + '° ' + $to)
}

function Main()
{
    # Main could either be an if-else structure or a switch-case structure
    If-Else
    Switch-Case
}

Main

Try It[edit]

Copy and paste the code above into one of the following free online development environments or use your own PowerShell compiler / interpreter / IDE.

Online[edit]

  • There are some options, but none are fully functional at this time.

Windows[edit]

macOS / Linux[edit]

See Also[edit]