Programming Fundamentals/Conditions/PowerShell

Contents

# 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/ConditionsfunctionGet-Choice(){Write-Host"Enter C to convert to Celsius or F to convert to Fahrenheit:"$choice=Read-Hostreturn$choice}functionGet-Temperature($label){Write-Host"Enter $label temperature:"$temperature=Read-Hostreturn$temperature}functionCalculate-Celsius($fahrenheit){$celsius=([double]$fahrenheit-32)*5/9return$celsius}functionCalculate-Fahrenheit($celsius){$fahrenheit=[double]$celsius*9/5+32return$fahrenheit}functionDisplay-Result($temperature,$from,$result,$to){Write-Host$($temperature+'° '+$from+' is '+$result+'° '+$to)}functionMain(){# Main could either be an if-else structure or a switch-case structure$choice=Get-Choice# If-Else approachif($choice-eq'C'-or$choice-eq'c'){$temperature=Get-Temperature"Fahrenheit"$result=Calculate-Celsius$temperatureDisplay-Result$temperature"Fahrenheit"$result"Celsius"}elseif($choice-eq'F'-or$choice-eq'f'){$temperature=Get-Temperature"Celsius"$result=Calculate-Fahrenheit$temperatureDisplay-Result$temperature"Celsius"$result"Fahrenheit"}else{Write-Host'You must enter C to convert to Celsius or F to convert to Fahrenheit.'}# Switch-Case approachswitch($choice){C{$temperature=Get-Temperature"Fahrenheit"$result=Calculate-Celsius$temperatureDisplay-Result$temperature"Fahrenheit"$result"Celsius"}F{$temperature=Get-Temperature"Celsius"$result=Calculate-Fahrenheit$temperatureDisplay-Result$temperature"Celsius"$result"Fahrenheit"}default{Write-Host'You must enter C to convert to Celsius or F to convert to Fahrenheit.'}}}Main