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 While, For, 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.
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.
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.
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.
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.
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.
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.
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.
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.
$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.
$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.
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]
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.