Refactored Codes
Powershell - Learn positional parameter, switch expression, mandatory parameter, reading parameter from pipeline by creating a calculator
Today we are going to write a powershell script, which provides basic calculator features.
List of operations are :
  1. Add
  2. Subtract
  3. Multiply
  4. Division
You can watch me coding on youtube.
[embed]https://youtu.be/DpYy7A4om8A[/embed]
This article will help us understand few of the powershell features.
  1. switch expression
  2. Positional Parameters
  3. Value From Pipeline By Property Name
  4. Making a parameter Mandatory
  5. Providing a set of valid values to choose from
This is a small example, but will help you learn a lot of other features.
Let us do this step by step.
We will first define a function with 3 parameters.
  1. First Parameter is of type int and name $FirstName.
  2. Second Parameter is of type int and name $SecondName.
  3. Third Parameter is of type string and name $Operation.
And, we use Write-Output to print a string to check if the function call is working or not.
And, save the file as Calculator.ps1
function calculator {
    param(
     [int] $FirstNumber,
     [int] $SecondNumber,
     [string] $Operation
    )

    Write-Output "Calculator Function Called";
}
Load the function into the terminal using .    .\Calculator.ps1
Then, type calculator, this is function name, and hit Enter.
You should be able to see Calculator Function Called.
Ok, this means our function was defined properly and our setup is working.
Now, we are going to add the core calculator logic.
We use switch statement to perform different operation based on $Operation.
We are using $Operation variable as switch value.
We have four operation supported in the calculator.
  1. Add
  2. Subtract
  3. Multiply
  4. Divison
After adding switch expression the code looks like this. Right now, our script is ready to work as calculator.
function calculator {
    param(
        [int]$FirstNumber,
        [int]$SecondNumber,
        [string]$Operation
    )


    $result = switch($Operation) {
               Add { $FirstNumber + $SecondNumber }
               Subtract { $FirstNumber - $SecondNumber }
               Multiply { $FirstNumber * $SecondNumber }
               Divison { $FirstNumber / $SecondNumber }
              }

     return $result;
}
To load the fresh function definition, reload the powershell script file like this .     .\Calculator.ps1;
After that you can use calculator command to check if the code is working or not
PS D:\LearningPowerShell> calculator -FirstNumber 2 -SecondNumber 3 -Operation Add
5
PS D:\LearningPowerShell> calculator -FirstNumber 2 -SecondNumber 3 -Operation Multiply
6
PS D:\LearningPowerShell> calculator -FirstNumber 2 -SecondNumber 3 -Operation Divison
0.666666666666667
PS D:\LearningPowerShell> calculator -FirstNumber 2 -SecondNumber 3 -Operation Subtract
-1
We have run the command with all the supported operations, one by one.
Now, our calculator function is working as expected.
Now, we will make improvement over this.
The First issue is User might call this function without the Parameters, as those parameters are not mandatory right now.
So, we will make all parameters mandatory.
We use Parameter's Mandatory attribute to make a parameter mandatory.
[Parameter(Mandatory)]
After making all parameters as mandatory, our code looks like below.
function calculator {
    param(
        [Parameter(Mandatory)]
        [int]
        $FirstNumber,

        [Parameter(Mandatory)]
        [int]
        $SecondNumber,

       [Parameter(Mandatory)]
       [string]
       $Operation
    )


    $result = switch($Operation) {
               Add { $FirstNumber + $SecondNumber }
               Subtract { $FirstNumber - $SecondNumber }
               Multiply { $FirstNumber * $SecondNumber }
               Divison { $FirstNumber / $SecondNumber }
            }

     return $result;
}
  We have made it mandatory for the user to provide values for the parameters. Now, we have to make sure that the user is only able to choose values of $Operation from a given set of values.
Currently the user can type any value they want, but we don't handle infinite number of Operation,
That's why we are going to provide a set of values for $Operation.
We use ValidateSet to provide the set of values, which are allowed by script.
And one added benefit is, this will also provides us with Commandline Tab completion in the terminal.
We added below values to the $Operation parameter.
[ValidateSet('Add', 'Subtract', 'Multiply', 'Divison')]
Now our code looks like this.
function calculator {
    param(
        [Parameter(Mandatory)]
        [int]
        $FirstNumber,

        [Parameter(Mandatory)]
        [int]
        $SecondNumber,

        [Parameter(Mandatory)]
        [ValidateSet('Add', 'Subtract', 'Multiply', 'Divison')]
        [string]
        $Operation
    )


    $result = switch($Operation) {
               Add { $FirstNumber + $SecondNumber }
               Subtract { $FirstNumber - $SecondNumber }
               Multiply { $FirstNumber * $SecondNumber }
               Divison { $FirstNumber / $SecondNumber }
             }

    return $result;
}
We can add one more feature, where this function can be used in pipeline.
To do that, we have to set ValueFromPipelineByPropertyName attribute of Paramter.
After, adding these modifiers, we can use our function as part of a pipeline.
And, Now the code looks like this.
function calculator {
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [int]
        $FirstNumber,

       [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
       [int]
       $SecondNumber,

       [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
       [ValidateSet('Add', 'Subtract', 'Multiply', 'Divison')]
       [string]
       $Operation
    )


    $result = switch($Operation) {
                   Add { $FirstNumber + $SecondNumber }
                   Subtract { $FirstNumber - $SecondNumber }
                   Multiply { $FirstNumber * $SecondNumber }
                   Divison { $FirstNumber / $SecondNumber }
             }

    return $result;
}
 
Now you can run code like this.
// command to run
> [pscustomobject]@{ FirstNumber=12; SecondNumber=12; Operation='Multiply' } | calculator;

-- output
> 144
In the above command [pscustomobject]@{ FirstNumber=12; SecondNumber=12; Operation='Multiply' } is a an powershell object.This object gets passed to calculator function using pipe.
Now, our calculator is working with pipeline.
We can make a change to display output better visually.
We can return an object from the function.
Objects are displayed better visually in Powershell, so, now our calculator  will have better output display.
After returning an object, the code looks like this.
function calculator {
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [int]
        $FirstNumber,

        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [int]
        $SecondNumber,

        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [ValidateSet('Add', 'Subtract', 'Multiply', 'Divison')]
        [string]
        $Operation
)


    $result = switch($Operation) {
                   Add { $FirstNumber + $SecondNumber }
                   Subtract { $FirstNumber - $SecondNumber }
                   Multiply { $FirstNumber * $SecondNumber }
                   Divison { $FirstNumber / $SecondNumber }
                }

     return [pscustomobject]@{ FirstNumber=$FirstNumber; SecondNumber=$SecondNumber; Operation=$Operation; Result=$result };
}
This is how it looks like in Powershell.
This shows output of calculator program.
This ends this article.
I hope, as a reader you learnt something from this.