0

I'm trying to print a warning to let the user know that 0 isn't a valid option for an assignment for class. Just started learning about powershell and can't find any help on how to set a parameter like this.

Assignment is 3.) Write a loop that calculates $num^2 for each iteration and prints the value using Write-Host. This loop must execute at least once and beginning counting down. When $num = 0, the loop should end. Prevent this loop from receiving $num as 0 as this will cause an infinite loop. If 0 is set as $num, print a warning to let the user know that 0 isn’t a valid option.

So far this is what I have

$num=Read-Host -Prompt 'Enter a number'
do
{
   write-host $num
   $num--
}
until($num -eq -1)

Any help would be greatly appreciated

v42
  • 1,415
  • 14
  • 23
Aeolos
  • 1
  • Use a while loop and break statement to exit when you need to. There is no squaring in your try – Jawad Feb 13 '20 at 22:07

2 Answers2

0

There are two fundamental problems:

  • Read-Host always returns a string, and --, the decrement operator, can only be used on numbers; you must convert the string to a number first:

    • [int] $num = Read-Host 'Enter a number'
  • write-host $num $num-- doesn't work as expected: while the $num references are expanded, the trailing -- is considered a string literal, not the decrement operator; to treat $num-- as an expression, you must enclose it in (...); also, to print the already decremented number, reverse the operands:

    • $num = 42; Write-Host ($num--) $num yields 42 41, as intended.
    • Incorrect: $num = 42; Write-Host $num $num-- yields 42 42--
    • The - complex - rules PowerShell uses when parsing unquoted command arguments are summarized in this answer
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Try this:

$num = Read-Host -Prompt 'Enter a number'
$num = [int]::Parse( $num )

do
{
   write-host "$num square is $([Math]::Pow($num,2))" 
}
while(--$num)
f6a4
  • 1,684
  • 1
  • 10
  • 13