Tag Archives: dotnethelpers.com

How to get the array as input using Powershell

To read an array into Read-Host (get the array as input), you would need to put it in a loop because anything entered into Read-Host will be interpreted as a string. To make output in new line we can use $OFS, which is a special variable in PowerShell . OFS stands for Output field separator . You would use this to separate object/Array.

The .split() method is self explanatory, the .trim() method will simply remove leading and trailing spaces and leading and trailing line breaks

Example #1 : Getting Value as an Array by Looping

$arrayInput = @()
do {
$input = (Read-Host "Please enter the Array Value")
if ($input -ne '') {$arrayInput += $input}
}
#Loop will stop when user enter 'END' as input
until ($input -eq 'end')

$arrayInput

OUTPUT:

Example 2# : Alternative approach for handling the multiple inputs without loop.

#Set New line using OFS special Powershell variable
$OFS = "`n"
#Externally set input value as string
[string[]] $_ServerList= @()
#Get the input from the user
$_ServerList = READ-HOST "Enter List of Servers"
#splitting the list of input as array by Comma & Empty Space
$_ServerList = $_ServerList.Split(',').Split(' ')
$OFS + $_ServerList

Output:

PowerShell : Continue Keyword

Continue Keyword in PowerShell

One of the things that is a bit confusing for powershell beginner is the Continue statement. This is partially because it does not act like it might in some other languages. Next question will arise, then what does the Continue statement do in Windows PowerShell? the answer is it returns flow to the top of the innermost loop that is controlled by a WhileFor, or Foreach statement. 

Example:

In the following example, program flow returns to the top of the While loop if value of $myValue variable is equal to 6. As a result, all the numbers between 1 and 10 are displayed except for 5:

while ($myValue -lt 10)
{
$myValue += 1
if ($myValue -eq 6) {Continue}
Write-Host $myValue 
}

Output:

1
2
3
4
5
7
8
9
10

The Continue keyword supports labels. A label is a name you assign to a statement in a script, so the continue will skip in the current loop and execute form the  assigned label location. Let we discuss more about the labels in upcoming articles.

Power Shell – Containment Operators

Power Shell Containment Operators

The containment operators (-contains and -notcontains) are similar to the equal operators. However, the containment operators always return a Boolean value, even when the input is a collection. The conditional operator -Contains is similar to -eq, except it returns ‘True’ or ‘False’. -Contains is designed for situations where you wish to test for one particular item in a collection, array or a hash table.

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

contains

Always returns a Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values. When the test value is a collection, the Contains operator uses reference equality. It returns TRUE only when one of the reference values is the same instance of the test value object.

Syntax: <Reference-values> -contains <Test-value>

Example: 1

Contains checks each item between the commas

$Name = "John", "Ray Matt", "Anthony" 
$Name -Contains "Ray Matt"

OUTPUT

True

Example: 2

-Contains requires exact equality

$Name = "John", "Ray Matt", "Anthony" 
$Name -Contains "Ray"

OUTPUT

False

-notcontains

The negative -NotContains is not as useful as -NotMatch. However, from what we have already learned the syntax is predictable.

Syntax: <Reference-values> -notcontains <Test-value>

Example:

$Name = "John", "Ray Matt", "Anthony" 
$Name -notContains "Ray"

OUTPUT

True

-in Operator

In operator return the boolean value if the test value appears in a collection of reference values. Always return as Boolean value. Returns TRUE only when the test value exactly matches at least one of the reference values else it will returns FALSE.

Syntax: <Test-value> -in <Reference-values>

Example: 1

$Name = "John", "Ray Matt", "Anthony" 
"Ray" -in $Name

Output:

False

Example: 2

$Name = "John", "Ray Matt", "Anthony" 
"Ray Matt" -in $Name

Output:

True

-notin Operator

In operator return the boolean value if the test value appears in a collection of reference values. Always return as Boolean value. Returns TRUE only when the test value not a exactly matches at least one of the reference values else it will returns FALSE.

Syntax: <Test-value> -notin \<Reference-values>

Example: 1

$Name = "John", "Ray Matt", "Anthony" 
"Ray" -in $Name

Output:

True

Example: 2

$Name = "John", "Ray Matt", "Anthony" 
"Ray Matt" -in $Name

Output:

False

PowerShell : Do-While & Do-Until Loop

Do-While & Do-Until Loop in PowerShell

Loops are an essential construct in any programming language as they enable a block of code to be repeatedly executed based on the condition. This can be useful for iterating through items in an object or repeatedly performing an operation. PowerShell supports involves setting a condition which either allows the loop to process as long as the condition is true or until it is met. 

  • The Do keyword works with the While keyword or the Until keyword to run the statements in a script block, up to the condition. The script block in a Do loop always runs at least once.
  • In a Do-While loop, the condition is evaluated after the script block has run. Then the while loop repeat the script until as long as the condition became false.
  • In a Do-Until loop always runs at least once before the condition is evaluated. However, the script block runs as long as the condition is false.

Do-While

Syntax : do {<statement list>} while (<condition>)

Example:

In below example, the loop will stop executing if condition became false that is if loop_index value reach 0 then condition became false.

$myArray = 1,2,3,0,4
do
{
$loop_index++;
}
while ($myArray[$loop_index] -ne 0)
$loop_index

Output:

3

Do-Until

Syntax : do {<statement list>} until (<condition>)

Example:

In below example, Do…Until loop is used when we want to repeat a set of statements as long as the condition is false.

$myArray = 1,2,3,0,4
do
{
$loop_index++;
}
until($myArray[$loop_index] -ne 0)
$loop_index

Output:

4

 

Power Shell – Type comparison

What is comparison Operator?

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.

Type comparison

The type comparison operators (-is and -isnot) are used to determine if an object is a specific type.

Operators  Description
-is Returns true if both object are the same type
-isnot Returns true if the objects are not the same type

-is Operator

Syntax: <object> -is <type reference>

Example:

PS C:\>
$stringMsg1 = "dotnet-helpers"
$stringMsg2 = 100
$stringMsg1 -is $stringMsg2.GetType()
$stringMsg2 -is [int]

OUTPUT

False
True

-isnot Operator

Syntax: <object> -is <type reference>

Example:

PS C:\>
$stringMsg1 = "dotnet-helpers"
$stringMsg2 = 100
$stringMsg1 -isnot $stringMsg2.GetType()
$stringMsg2 -isnot [int]

OUTPUT

True
False

PowerShell – Replacement Operator

Replacement Operator

PowerShell provides several options to help you replace text in a string with other text. The -replace operator replaces all or part of a value with the specified value using regular expressions. It replaces every occurrence of the exact string you specify with the exact replacement string that you provide. The -replaceoperator provides much more flexibility because its arguments are regular expressions that can match and replace complex patterns.

Operators  Description
-replace replace a string pattern


Syntax:

<input> <operator> <original> <substitute>

The syntax of the -replace operator is as follows, where the <original> placeholder represents the characters to be replaced, and the <substitute> placeholder represents the characters that going to replace.

Example:

PS C:\> 
$stringMsg = "Hi Welcome to dotnet-helpers.com"
$stringMsg -replace 'Hi' , "You are"

OUTPUT

You are Welcome to dotnet-helpers.com

By default, the -replace operator is case-insensitive. To make it case sensitive, you need to introduce ‘c’ as prefix like  -creplace. To make it explicitly case-insensitive, you need to prefix ‘it’ like -ireplace.

Example:

Here the output will be same text beacuse we maked a replace operator as case sensitive, so ‘HI’ does’t macth with the string.

PS C:\>
$stringMsg = "Hi Welcome to dotnet-helpers.com"
$stringMsg -creplace 'HI' , "You are"

OUTPUT

Hi Welcome to dotnet-helpers.com

PowerShell – Matching Operators

-like and -notlike Operators

The like operators find elements that match or do not match a specified pattern using wildcard expressions.

How its handle single & Collection values?

If we input scalar value, comparison operators return a Boolean value. When the input is a collection of values, the comparison operators return any matching values. If there are no matches found in a collection then the comparison operators do not return anything.

The syntax is:

<string[]> -like <wildcard-expression>
<string[]> -notlike <wildcard-expression>

Example:1

PS C:\>

$singleValue = "Aadharsh"
$singleValue = $singleValue -like "Aadharsh"
Write-Host ""
Write-Host "Is varible contain 'Aadharsh' : " $singleValue

OUTPUT:

Is varible contain 'Aadharsh' : True

Example:2

$singleValue = "Aadharsh" , "Rakshu"
$singleValue = $singleValue -like "Aadharsh"
Write-Host ""
Write-Host "The matched value is : " $singleValue

OUTPUT:

The matched value is : Aadharsh

-match and -notmatch Operators

The match operators find elements that match or do not match a specified pattern using regular expressions. It search only in strings and they can’t search in arrays of integers or other objects.

The syntax:

<string[]> -match <regular-expression>
<string[]> -notmatch <regular-expression>

Example:1

PS C:\>

$singleValue = "Aadharsh"
$singleValue = $singleValue -match "Aadharsh"
Write-Host ""
Write-Host "Is variable contain 'Aadharsh' : " $singleValue

OUTPUT:

Is variable contain 'Aadharsh' : True

Example:2

$singleValue = "Aadharsh" , "Rakshu"
$singleValue = $singleValue -like "Aadharsh"
Write-Host ""
Write-Host "The matched value is : " $singleValue

OUTPUT:

The matched value is : Aadharsh

Note:

There is automatic variable called “matches” element which return the match elements. You can use $matches variable to get the matched value.

What is difference between -Like & -Match?

The most technical distinction is -Match is a regular expression, whereas -Like is just a wildcard comparison, a subset of -Match. If you need a wildcard to find this item’, then start with -Like. However, if you are sure that most of the letters in the value that you are looking for, then you are better you can go with -Match. -match operator is quite faster than -like operator.

PowerShell – Equal Operators

Equal Operators:

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”

Operators  Description
-eq equals
-ne not equals
-gt greater than
-ge greater than or equal
-lt less than
-le less than or equal

 

Example:

$userName = 'Rakshu'
$userName -eq 'rakshu'

$userName = 'Aadharsh'
$userName -ne 'rakshu'

$number1 = 100
$number1 -gt 50

$userName = 100
$userName -le 50

OUTPUT:

PowerShell Basics: Comparison Operators and Conditional Logic

Comparison Operators and Conditional Logic

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
-match Returns true when string matches regex pattern – $matches contains matching strings
-notmatch 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.

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