Monday, 5 July 2021

PowerShell: Calculate the power using math function

 Here is a Powershell script 

  • which gets two numbers from the command line 
  • if there is no parameters, read them from the keyboard
  • Calculate the power (first param on the power of the second )
  • Display the output
  • E.g. .\calcPower.ps1 2 3 => 8

 

PowerShell Script:


                    

#assign argument values
$num1 = $args[0]
$num2 = $args[1]

#check if the value entered is null
if ($num1 -like "$null"){
    #if null, ask for user input
    $num1 = read-host "Please enter the 1st number"
}

if ($num2 -like "$null"){
    $num2 = read-host "Please enter the 2nd number"
}

#calculate power using 'pow' function
$power = [Math]::Pow($num1,$num2)

#display output
Write-Output "$num1 to the power $Num2 is $power"