All posts by Thiyagu

PowerShell – Sorting in Array

Sort array:

It’s very easy of arranging the elements of an array in a order with PowerShell. Just we need to do is pipe the output of an array to the Sort-Object cmdlet: The default sort order is ascending : the numbers range from small to large. To perform a descending sort requires utilizing the Descending switch.

Example:

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
#Display the list of furits
Write-Host "";
$myFavFruits | sort

We can also sort based on our requirement by using “ascending” or “descending” cmdlet.

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
#Display the list of furits
Write-Host "";
$myFavFruits | sort -descending

Select top elements in Array:

In this case, the sorted output is piped to the Select-Object cmdlet to select the top five elements/values as shown like below.

Example:

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
#Display the list of furits
Write-Host "";
Write-Host "Top 3 fruits";
$myFavFruits | Sort-Object | select -First 3

You can sort on any object property like name, date… on single properties or  multiple properties. It can be used by separate them with commas:

$myFavFruits | Sort-Object | Status , DisplayName

Remove Duplicate Entries in Array:

Another way to use the Sort-Object cmdlet is to sort on a property using the -Unique parameter to eliminate duplicates and return a set of unique values.

$myFavFruits | sort -Unique

Sort by Case Sensitive:

The another important point to know about Sort-Object is that sorting is case insensitive by default. Case-sensitive sorting isn’t used too often, but let we see simple demonstrate how it works in case the need arises. If you want to force the sort to be case sensitive, you need to include the Case-sensitive parameter as like below.

$myFavFruits | sort Startname -Unique -CaseSensitive

Delete arrays and elements:

Even though most of the array operations in PowerShell are relatively easy to accomplish, no convincing solution exists for removing specific elements or deleting complete arrays. The easiest way to get rid of an entire array is to assign the variable $null:

$myFavFruits = $null

Powershell Array

By default, PowerShell assumes that the elements of an array are of the type variant. This means that you can mix different data types—that is, combine numerical values, dates, or strings in a single variable. The data elements of a PowerShell array need not be of the same type, unless the data type is declared (strongly typed). However, if you think to restrict an array to a certain data type then you can declare the array as like below:

[int[]] $scoreRange = 1,2,3,4,5,6,7,8,9
$scoreRange

From the above code snippet, $scoreRange will print like one by one manner. Notice that a above declaration is insufficient. You also have to assign values to the variable. If the data types don’t match then it will throw an error.

Output:

In alternatively we can also use the below script for assigning the consecutive numerical values.

[int[]] $$scoreRange = 1 .. 9
$scoreRange

Simplified Syntax:

We can explicitly declare the array as like below

$myFavFruits= @("Banana","Orange","Apple","Mango")

Under normal circumstances, you would want to avoid the additional effort of this notation. However, it helps you understand why you can create an empty array in PowerShell with this command:

$myFavFruits = @()

In many cases, you won’t assign values manually to an array. Instead, you will want to store the output in a variable. If the output is an array, there we can use above empty array explicitly.

Add elements to an array

If you later want to add elements to an array then you want to use operator “+” .

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
$myFavFruits

This can also be written as below. And we can also combined the array.

$myFavFruits += "orange"
#Combined Array
$myFavFruits += $yourFavFruits

Display the contents of an array

If you want to display the elements of an array, you usually don’t need a loop. In the simplest just enter the variable name to make them display all values of the array. As like other programming language, we can able access the value by its index like below:

Example

$myFavFruits= @("Banana","Orange","Apple","Mango")
$myFavFruits = $myFavFruits + "Guva"
#Display the list of furits
Write-Host "";
Write-Host "List of my favorite fruits are $myFavFruits "
Write-Host "";
Write-Host "Most favorite fruit is" $myFavFruits[1]

PowerShell Comments

Same like other programming language, the comments in Powershell will not executed. Comments can be added to explain the function of the code and it can  be placed anywhere and anything between them will be treated as a comment. The powershell also supports single line and multi line comments.

Single Line Comments

SYNTAX: #

The comment with the # will handling single line comments. In PowerShell single line comments start with a hash symbol and everything to the right of the # will be ignored.

$MyFirstVaiable = "Hello" #Example for single line comments.

Multi-line Comments

Begin the comment with the <# tag, and end the comment with the #> tag for handling multiline. Multi-line comments are typically used to add descriptive help at the start of a script.

SYNTAX: <# #>

$MyFirstVaiable = "Hello" <# Example for Multiple line comments. 
                  This variable use to display hello #>

 

Working with PowerShell’s Data Types

An important property of a PowerShell variable is its name, which is always preceded by the dollar sign “$” and can only contain letters, numbers, and the underscore. If you feel a strong urge to use other characters, you have to enclose the name in curly braces. You should not use the name of variables that have been pre-defined.

Windows PowerShell uses the Microsoft .NET Framework data types. The poweshell can supports strings ,integers ,floating point numbers, strings, and Boolean values.You don’t have to explicitly declare the data type of a variable, the PowerShell automatically chooses the data type for you when you initialize the variable—that is,when you first assign a value.

Example: 1 

$GetNumber = Read-Host "Please enter you score" 
$Total = $GetNumber + $GetNumber
Write-Host "The Total Score is $Total"

PowerShell wrongly assumed that the data type of the variable $GetNumber is String. Because the arithmetic operator + is overloaded (the implementation of the operator depends on the arguments), the second line in the program add a string instead of a number.

The second argument of the operator + always has to be a number, so PowerShell automatically converts the data type of $GetNumber into Int32. However, the first argument can also be a string. The result is that PowerShell determines the value of the expression “5”+5, which is 55 ( concatenate the string). 

Example: 2

[INT]$GetNumber = Read-Host "Please enter you score" 
$Total = $GetNumber + $GetNumber
Write-Host "The Total Score is $Total"

In the above code snippet, we explicitly declared the number as Int32 (integer) by enclosing the type name in square brackets before the variable name. So the above variable is called “strongly typed”. If you declare the variable’s data type implicitly in our script the the variable is called as weakly typed.

Data Types:

Data Type Name Description
[Array] Array
[Bool] Value is TRUE or FALSE
[DateTime] Date and time
[Guid] Globally unique 32-byte identifier
[HashTable] Hash table, collection of key-value pairs
[Int32], [Int] 32-bit integers
[PsObject] PowerShell object
[Regex] Regular  expression
[ScriptBlock] PowerShell script block
[Single], [Float] Floating point number
[String] String
[Switch] PowerShell switch parameter
[TimeSpan] Time interval
[XmlDocument] XML document

Note: 

  • Windows PowerShell uses the Microsoft .NET Framework data types.
  • We don’t have to rely on PowerShell’s ability to automatically convert data types if we tell the interpreter that we are expecting a number as input.
  • This ensures that our script works as intended.
  • The explicitly declaring variable types can prevent unwanted results in your scripts and makes them more reliable.

PowerShell’s Variables

Windows PowerShell is designed to be an interactive command-line shell and it’s also a programming language. A PowerShell script is really nothing more than a simple text file. The file contains a series of PowerShell commands, with each command appearing on a separate line.

If we need to run the PowerShell script using the notepad then its filename needs to save as .PS1 extension.

Powershell Variables

Is It Case Sensitive

The answer is “YES”, power shell comments are case sensitive. 

  • As like other programming language, we need to declare the variable as like below. The main difference is we need to add prefix with ‘$’ symbol in the variable.
  • All we have to do to declare those variables is add a dollar sign, then use whatever name for the variable we want and no spaces are allowed in the variable name.

Example : 1

$name = 'Jon'
$number = 12345
$myGrade= 'D+'
$location = 'Charlotte'
// if we declare as string then it will treat as single word
$listofnumbers = 6,7,8,9

Example : 2

//Assign text to varible
$myFirstVarible = "Dotnet-helpers Welcomes you"
//Print the variable
$myFirstVarible 
//Concatenate Variable
$mySecondVarible = $myFirstVarible + "for PowerShell learning Curve" 
$mySecondVarible

Example : 3 Handling Dynamic Variables.

The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter.

$UserAnna= “This is specific MSG for Anna”
$inputUser=”Anna"
$msgAnna = $(("User"+ $inputUser))
#-ValueOnly : Indicates that this cmdlet gets only the value of the variable.
Get-Variable -Name "$msgAnna" -ValueOnly

OUTPUT: This is specific MSG for Anna

 

Getting Help Information

The PowerShell includes detailed Help topics that explain PowerShell concepts. There are also Help topics for each cmdlet and provider and Help topics for many functions and scripts.

Getting Help for Cmdlets

To get Help about Windows PowerShell cmdlets, use the Get-Help cmdlet. Here let we see some of the cmdlets help.

To get a list of all the cmdlet Help topics in your session use below,

get-help -category cmdlet

OUTPUT

If we want to display one page of each Help topic at a time, then we need to use the help function or its alias man. For example, to display Help for the Get-ChildItem cmdlet, type

Man Get-ChildItem/Help Get-Childitem

If we need to known about all content in the Help topic, below cmdlet will help us with help of FULL keyword

get-help get-childitem -full

Getting Help About Providers

To get Help for a provider, type “Get-Help” followed by the provider name. For example, to get Help for the Registry provider, then type like below

get-help registry

To get all the list of provide use below

get-help -category provider

Getting Help About Functions and Scripts

We also use the help topics for many scripts and functions in Windows PowerShell. To display the Help for a function, type “get-help” followed by the function name.

get-help disable-psremoting

Getting Help Online

If we want to find the help online through the powershell then its can be acheive by the below command.

get-help <command-name> -online

For example, to get the online version of the Help topic about the Get-ChildItem cmdlet, type:+

get-help get-childitem -online

 

How to validate the version of installation

We can use $PSVersionTable.PSVersion to determine the engine version. If the variable does not exist is shown then it is safe to assume the engine is version 1.0

We also use,$Host, get-host , $PSVersionTable to get deep information about our power shell tool. Please find the snap for how to get the details.

What’s New With PowerShell

Windows PowerShell® 5.0 includes significant new features that extend its use, improve its usability, and allow you to control & manage Windows-based environments more easily. Windows Server 2012 R2 introduced the notion of Desired State Configuration, PowerShell 5.0 advances this concept through OneGet.

  • OneGet is a new module which way to search and install hundreds of software packages from the repository and this is known Chocolatey repository.
  • It is a package manager for Windows. It’s mission to be a framework for installing applications and tools that you need for a Windows computer.
  • It uses PowerShell to deliver packages built on the NuGet infrastructure.

Flow of using repository

  • List and manage software repositories for packages that can be installed.
  • Search and filter your repositories.
  • Install/uninstall packages from windows using the repositories.
  • Get started with the command: Import-Module -Name OneGet.

Installing Windows PowerShell in window’s 8.1

  • Windows PowerShell 5.0 is installed by default on Windows Server 2016 Technical Preview and Windows 10. 
  • To install Windows PowerShell 5.0 on Windows Server 2012 R2/Windows 8.1 Enterprise/Windows 8.1 Pro we need to download and install Windows Management Framework 5.0 here  
  • Don’t forgot to read the download details and meet all system requirements before starting your installation.

Windows Management Framework 5.0 Contains?

  • Contains updates for Windows PowerShell and Windows PowerShell ISE.
  • Package Management cmdlets.
  • Network Switch cmdlets.
  • Windows PowerShell Desired State Configuration (DSC)

To uninstall Windows Management Framework 5.0:

Navigate to the Control Panel\Programs\Programs and Features\Uninstall a program. You are looking for Windows Management Framework 5.0.

 

Windows PowerShell System Requirements

This topic we are going to discuss about the system requirements for Windows PowerShell 5.0 and its special features, such as Windows PowerShell Integrated Scripting Environment (ISE), CIM commands, and workflows.

Note:

Windows® 8.1 and Windows Server® 2012 R2 include all required programs so no need to install any thing special to work on powershell. This topic is designed for users of earlier releases of Windows. Windows PowerShell 4.0 runs on Windows 8.1, installed by default.

Operating System Requirements

  • Windows PowerShell 5.0 runs on the following versions of Windows.
  • Windows Server 2016, installed by default
  • Windows Server 2012 R2, install Windows Management Framework 5.0 to run Windows PowerShell 5.0
  • Windows Server 2012, install Windows Management Framework 5.0 to run Windows PowerShell 5.0
  • Windows Server 2008 R2 with Service Pack 1, install Windows Management Framework 5.0 to run Windows PowerShell 5.0
  • Windows 8.1 Windows 7 with Service Pack 1, install Windows Management Framework 5.0 to run Windows PowerShell 5.0

Microsoft .NET Framework Requirements

Windows PowerShell 5.0 requires the full installation of Microsoft .NET Framework 4.5. Windows 8.1 and Windows Server 2012 R2 include Microsoft .NET Framework 4.5 by default.

 

Introduction to Window’s PowerShell

Windows PowerShell is one of the most important Windows Server management tools that Microsoft has released. Windows PowerShell is one of the most important Windows Server management tools that Microsoft has released. An entirely new scripting environment for Windows, it consists of a new command shell and a new scripting language.We can write PowerShell scripts using any text editor, but you must need the PowerShell command shell for running.

Why its called Window Server Management?

Although PowerShell has been important in the Microsoft ecosystem ever since its release, as Windows Server 10 comes closer to release,we find that many features and deployments are significantly easier and more full-featured when carried out with PowerShell.  

How to get License?

PowerShell is built into Windows, so there is no fee or additional licensing cost. 

More about PowerShell:

Windows PowerShell is a command-line shell and scripting language designed specially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment. In PowerShell, administrative tasks are generally performed by cmdlets, specialized .NET classes implementing a particular operation. Sets of cmdlets may be combined together in scripts; executables, which are standalone applications; or by instantiating regular .NET classes.

Power shell versions: 

PowerShell Version Release Date Default Windows Versions
2.0 October 2009 Windows 7 Windows Server 2008 R2
3.0 September 2012 Windows 8 Windows Server 2012
4.0 October 2013 Windows 8.1 Windows Server 2012 R2
5.0 April 2014 Windows 10