The equal operators return a value of TRUE if its identical or return a value of FALSE if it is not identical. The entire pattern must match an entire value. By default, all comparison operators are case-insensitive. To make a comparison operator case-sensitive, precede the operator name with a “c”. For example, the case-sensitive version of -eq is -ceq. To make the case-insensitivity explicit, precede the operator with an “i”
Comparison operators let you specify conditions for comparing values and finding values that match specified patterns. To use a comparison operator, specify the values that you want to compare together with an operator that separates these values.
Equality
Operators
Description
-eq
equals
-ne
not equals
-gt
greater than
-ge
greater than or equal
-lt
less than
-le
less than or equal
Containment
Operators
Description
-contains
Returns true when reference value contained in a collection
-notcontains
Returns true when reference value not contained in a collection
-in
Returns true when test value contained in a collection
-notin
Returns true when test value not contained in a collection
Matching
Operators
Description
-like
Returns true when string matches wildcard pattern
-notlike
Returns true when string does not match wildcard pattern
Returns true when string does not match regex pattern – $matches contains matching strings
Replacement
Operators
Description
-replace
replace a string pattern
Type comparison
Operators
Description
-is
Returns true if both object are the same type
-isnot
Returns true if the objects are not the same type
By default, all comparison operators in powershell’s are case-insensitive. If we need to make a comparison operator case-sensitive, precede the operator name with a “c”. For example, the case-sensitive version of -eq is -ceq. If we need to the case-insensitivity explicit, precede the operator with an i. For example, the explicitly case-insensitive version of -eq is -ieq. Let we discuss more about the each set of operators in upcoming articles.
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.
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:
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:
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.
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 “+” .
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]
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 #>
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.
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
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:+
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.
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.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.