Fundamental of Powershell Scripting



As a developer/programmer, if you have developed expertise in one programming language - learning another is just about understanding the syntax, the rest of the concepts are similar among all languages. So to get started developing automation scripts for Powershell, here are the things you care about:
  1. Read input & write output
  2. Data Types
  3. Operators
  4. Conditional Statements
  5. Looping Statement
  6. Functions 
  7. Object oriented scripting

Read input & write output

Output to console:
Lets start with "Hello World!", in powershell there are two ways to output to console:
  • Write-Host
  • Write-Output
The second one (Write-Output) is more preferred way to write to console as it does not destroy pipeline inputs. 

You can find the code here
Input from console:
Reading inputs from console is super easy in powershell.


Find the code above on my Github Gist here.

Data Types

Powershell is based on .NET Framework (and Powershell Core on .NET Core) and inherits all .NET CLR data types. The primative/values type available are:

  • byte
  • sbyte
  • short
  • ushort
  • int
  • uint
  • long
  • ulong
  • float
  • double
  • decimal
  • char
  • bool
  • Datetime


Find the code above on my GitHub Gist here.

In Powershell, both single quote (') and double quote (") can represent string.However, single quote treat string as string literals while double quotes replace any placeholders as shown below.


Operator (Arithmetic, Comparison & Logical)

Arithematic:
Like any other language, Powershell also support common arithmetic operators like +, -, *, / and %.

Comparison:
The comparison operators share syntax with shell scripting like linux where -eq, -ne -gt, -lt, le and ge  are used in replacement of ==, !=, >, <, <= and >= respectively. 

Logical:
Powershell logical operators for And, Or  and not are -And, -Or, -Not or ! respectively.


Find the code above on my GitHub Gist here.

Conditional Statements

If Else statements:
Powershell conditional statements are really powerful. Lets start with if-else statements.



Switch:
Powershell switch conditionals are similar to many C like programming language. Unlike C#, powershell switch does not require break in the end of each case so you can evaluate multiple cases if you want.


Now here is how powershell switch statements are powerfull, by default powershell switch cases matches case-insensitively. You can make to match case-sensitive. One the most awesome things about powershell switch is wildcard based case matches. See example below:


The code for conditional statements can be found here.

Looping Statements

Powershell makes working with iteration really simple. Lets take a took at some example below:

For Loop: Perhaps this is the most common loop among many programming/scripting languages where loop execute statement/s for known number of iterations.



Foreach Loop: Powershell foreach loop is ideal for iterating over collection of objects.


While Loop: While loop keeps repeating set of instructions as long as the condition in while is true.



Do-While Loop: Just like in many other programming languages do-while also secures a place in Powershell and at atleast runs once a keep looping as long as the condition in while is true.



Do-Until Loop: This is a new category of loop that Powershell has introduced and exactly opposite of do-while loop. Where the loop keeps running until a specific condition is set to true. Like do-while loop it also executes atleast once.


The code examples for looping statements is available on my Gist github here.

Functions & CmdLets

Powershell functions share syntax with Javascript functions. Let see some quick example of basic functions. Below you can see 3 function examples, one that takes no arguments nor return anything, second that take an argument of type int but doesn't return anything and third that take an argument of type int and returns an int that is double of the value passed.


The code above is available here.

The functions we have seen above are generally not powershell style of writing function. In a standadrd powershell function parameters are passed through param. Let see some examples.


The script shown above is available here.

Lets go through it.

Example 1:  In Powershell, arguments are preferred to be defined under param function. Below you see a method that takes a parameter $text and if caller doesn't pass a value to it, default is set to NA string.



Example 2: As you have seen in previous example that a function can be called without passing a parameter but we also force the consumer to pass an argument. This is achieved using Parameter attribute passing in Mandatory value as shown below on line 13.



Example 3: When you are working with function you will often want to receive parameter input from pipes. We can take a value from the result of pipeline by using Parameter attribute passing in ValueFromPipeline as shown on line 22.



Example 4:  We can also force the caller to pass the function parameter a specific data type input. Below the function expects only integer input value from pipeline.



Example 5: Often value in the pipeline are complex object and cannot match by value since they don't have a common Type in those cases you might want to support parameter mapping of pipeline that only matches a property name so that if the object has a property field that matches with the parameter name of the function then it will bind successfully. This is achieved using Parameter attribute passing in ValueFromPipelineByPropertyName as shown on line 40 & 50.



Example 6: Sometimes you might want to specific short parameter names for convenience or probably want to change a parameter name and also want to support previous versions of your script (if you change parameter name and not specify an alias for the old name, someone who updates from older version of your script to newer version will break his code). You can specify an alias to deal that act as an alternate name to your parameter as shown in line 54 and used in line 57.


 The example shown above can be found here.

Object oriented scripting

Since Powershell is .Net based scripting and automation tool, it uses CLR and .Net runtime to execute scripts. Just as in C# everything inherits object class, powershell follows the same. Here is how you will create a new object in Powershell.


Lets also see a quick example of instantiating a .NET object and calling different methods on it.


On the example above we create an object of Queue defined in .NET namespace System.Collections then we enqueue two numbers, check counts and then dequeue one item. 

In Powershell, calling static method is done using :: as shown below. We use Math lib and calling its absolute method that return absolute of a number.


You can find the code for this section on my GitHub Gist here.

Comments

Post a Comment

Popular posts from this blog

Implementing Basic and JWT Token authentication with C# .NET

Setting up Free Custom Domain on Microsoft Azure Web App Service

.NET Core 3 officially comes to Windows IoT Core

Setting up CI and CD pipeline in Azure DevOps for ASP.NET Core and Azure Web Apps

Microsoft Azure DevOps : A Complete CI & CD solution in the cloud

Microsoft Azure Blob Storage - Managing Blobs and storage containers from C#

Xamrin Android Push Notification using Firebase Cloud Messaging

Securing Powershell Scripts with Code-Signing Certificate

Understanding Powershell ExecutionPolicy and securing Powershell CmdLets/Scripts with Code-Signing Certificate