Friday, May 3, 2013

Powershell DIY: Absolute Value

Absolute value. This
is the best possible simple example of an “if” “ElseIf” statement. An absolute value is the distance a number is
from 0. For 22 it is just that, 22. For -22, the absolute value is 22. In order to do this we are going to use the
read-host command to gather the requisite value:

$a = Read-Host “Number?”

With this statement we are defining $a by asking the user
with “Read-Host”. The “Number?” is purely
optional, but I always suggest using it to define the input. Next we need to use the “If” statement.

If

If must always be followed by a statement in parentheses:

If ()

For our conditional statement we are going to use the -le condition. We start with using the literal value of $a, ‘$a’
and the condition Less Than (-le) and define what exactly it is supposed to be
less than, 0:

If ('$a' -le 0)

So What if $a is less than 0? We subtract it from 0 of
course! Any negative number subtracted from 0 gives us the positive corresponding
value. Encapsulated in Braces ({}) we
spell out the math equation:

{$a = 0 - ($a)}

In order to address a negative value we must further
encapsulate it in parentheses, as we have done here. Our completed “If” statement is:

If ('$a' -le 0) {$a = 0 - ($a) }

Now we must address positive values to balance the
script. We use the “ElseIf” statement
for this:

ElseIf

And much like the “If” statement the condition is
encapsulated in Parentheses () and the action is encapsulated in braces ({}):

ElseIf(){}

The conditional statement here is similar to the previous if
statement, with one exception, the Less Than ( -le) has been replaced with a Greater
Than (-ge) condition:

ElseIf ($a -ge 0){}

Since this statement is for a positive number, we don’t want
it to actually do anything, so we balance both sides of the equation by making
an obvious statement $a = $a

ElseIf ($a -ge 0){$a = $a}

With this we have stated this: “If $a is greater than 0,
make $a equal $a.” In other words, Do nothing.
Last but not least, we tell the user the absolute value by using the
variable alone:

$a

Here is the Finished product:

$a = Read-Host "Number?"

If ('$a' -le 0) {$a = 0 - ($a) }

ElseIf ($a -ge 0) {$a = $a}

$a

I am sure there is a command that does all this out there,
but the purpose of this was to demonstrate math, addressing negative numbers,
and If “ElseIf” statements. As usual if
you have a better way to do this, let me know!
The fastest way to learning is through collaboration!