Part 8. PowerShell as a programming language (Operators and control instructions)

26 July 2023 25 minutes Author: Lady Liberty

Operators and Controls – A confident start with PowerShell

PowerShell is a powerful tool for working with scripts and automating tasks in the Windows environment. One of the most important aspects of programming in PowerShell is understanding the various statements and control statements that allow you to effectively control the flow of program execution. In our complete guide to operators and statements in PowerShell, you’ll learn about different types of operators, such as arithmetic, comparison, logical, assignment, string, and more. You’ll learn how to use these operators to perform a variety of operations, such as calculations, comparing values, checking conditions, working with variables, and more. In addition, we will look at various control statements, such as if-else conditional statements, switch statements, for, while, and do-while loops, which allow you to repeat actions in programs and handle different execution scenarios.

You will learn how to write effective scripts and automate routine tasks, which will make your work in the Windows environment much easier. Gaining an understanding of statements and control statements in PowerShell is key to achieving successful results in programming and automating tasks. Expand your knowledge and become a more efficient programmer with our complete guide! One of the features of PowerShell operators is their polymorphism, which allows you to apply the same operator to objects of different types. For example, the addition (+) and multiplication (*) operators can be applied to numbers, strings, and arrays. At the same time, the difference between PowerShell and many other object-oriented programming languages is that the behavior of operators for the main data types (strings, numbers, arrays and hash tables) is implemented directly by the interpreter, and not with the help of one or another method of objects of a certain type.

Arithmetic operators

The main arithmetic operators that are supported in the PowerShell shell are listed in the table. 8.1.

From the point of view of polymorphic behavior, the addition and multiplication operators are the most interesting. Let’s take a closer look at these operators.

The addition operator

As mentioned earlier, the behavior of the + and * operators for numbers, strings, arrays, and hash tables is determined by the PowerShell interpreter itself. As a result of adding or multiplying two numbers, a number is obtained. The result of adding (joining) two strings is a string. When two arrays are added, a new array is created that is the union of the arrays to be added.

And what will happen if you try to add objects of different types, for example, a number with a string? In this case, the behavior of the operator will be determined by the type of the operand on the left. It is necessary to remember the so-called right-handedness of left-handedness: the type of operands on the left determines the type of the operator’s result.

If the left operand is a number, PowerShell will attempt to convert the right operand to a numeric type.


PS С:\> 1+"12"
Как видим, строка ”12” была преобразована к числу 12. Результат действия оператора сложения — число 13. Теперь обратный пример, когда левый операнд является строкой:
PS С:\> "1"+12
Здесь число 12 преобразуется к строке ”12” и в результате конкатенации возвращается строка ”112”.
Если правый операнд нельзя преобразовать к типу левого операнда, то возникнет
PS С:\> 1+"а"
Не удается преобразовать значение "а” в тип ’’System. Int32”. Ошибка :*’’Входная
строка имела неверный формат.”
строка:1 знак:1
т 1+"а"
4 Categoryinfo : InvalidArgument: (:) [], RuntimeException
4- FullyQualifiedErrorld : InvalidCastFromStringToInteger

If the operand to the left of the addition operator is an array, then the operand to the right is added to that array. At the same time, a new array of type [object- [ ] ] is created, into which the contents of the operands are copied (this is due to the fact that the dimension is fixed). In the process of creating a new array, all restrictions on the types of added arrays will be lost. Let’s look at an example.

Let’s create an array of integers:

PS С:\> $а = [int[]J (1,2,3,4)
PS С:\> $а.getType().fullName
Если попробовать изменить значение элемента этого массива на какую-либо строку, то возникнет ошибка, т. к. элементами массива $а могут быть только целые числа:
PS С:\> $а[О]="ааа"
Не удается преобразовать значение "ааа" в тип "System.Int32”. Ошибка: "Входная
строка имела неверный формат."
строка:1 знак:1
+ $а[0]="ааа"
+ _——~~
+ Categoryinfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorld : InvalidCastFromStringToInteger
Добавим теперь к массиву $а еще один символьный элемент с помощью оператора
PS С:\> $a=$a+"abc"
Вновь попробуем изменить значение первого элемента массива $а, записав в него
символьную строку:
PS С:\> $а[0]="ааа"
PS С:\> $а
Как видим, теперь ошибка не возникает. Это связано с изменением типа массива $а:
PS С:\> $а.getType().fullName

The enlarged array $a has the type [object [ ] ], its elements can be objects of any type.

Now let’s move on to adding hash tables. As in the case of ordinary arrays, when adding hash tables, a new associative array is created into which elements from the added arrays are copied. In this case, both operands must be hash tables (type conversion is not supported here). The hash table elements to the left of the addition operator are first copied into the new array, followed by the hash table elements to the right. If the value of the key from the right operand is already found in the left operand, then an error will occur during addition.

Let’s consider an example:

PS С:\> $left=@{а=1;Ь=2;с=3}
PS С:\> $right=@{d=4;е=5}
PS С:\> $sum=$left+$right
PS С:\> $sum
d 4
а 1
b 2
е 5
с 3
Новая результирующая ХЭШ-таблица по-прежнему имеет ТИП System.Collections.
PS С: \> $sum. getType () . fullName

Multiplication operator

The multiplication operator can operate on numbers, strings, and regular arrays (the hash table multiplication operation is undefined). At the same time, there must be a number to the right of the multiplication operator, otherwise an error will occur. If there is a number to the left of the multiplication operator, then the multiplication operation is performed in the usual way:

PS С:\> 6*5
Если левым операндом является строка, то она повторяется указанное количество
PS С:\> "abc”*3
Если умножить строку на ноль, результатом будет пустая строка (тип
System, string, длина равна 0):
PS С:\> "abc"*0
PS С:\> (”abc"*0).getType().fullName
PS C:\> (”abc"*0).length
Аналогичным образом оператор умножения действует на массивы:
PS С:\> $а=1,2,3
PS С:\> $а=$а*2
PS С:\> $а

As in the case of the addition operator, when multiplying an array by a number, a new array of type [0bject [ ] of the required dimension is created and the elements of the original array are copied into it.

Subtraction, division and remainder from division operators

The subtraction (-), division (/), and remainder (e) operators in PowerShell are defined only for numbers. There is no special integer division operator: if you divide two integers, the result will be a real number (TYPE System. Doub1e).


PS С:\> 123/4 

If you want to round the result to the nearest integer, you just need to convert it to type [int].


PS С:\> [int](123/4)

It should be noted that PowerShell uses the so-called Bunker rounding when translating a real number into an integer: if the number is a half-integer (0, 5, 1, 5, 2, 5, etc.), then it is rounded to the nearest even number. Yes, the numbers 1.5 and 2.5 are rounded to 2, and 3.5 and 4.5 are rounded to 4. If the operands can be converted to numbers, PowerShell will perform the conversion.


PS С:\> "123"/4
PS С:\> 123/”4"
PS С:\> "123"/"4"

The subtraction operator can be applied to System variables. A Datetime that stores the date and time. For example, suppose that the variable $d 1 stores an object corresponding to the date March 8, 2021, and the variable $d 2 stores an object corresponding to the date February 23, 2021:

PS С:\> $dl=Get-Date -Year 2021 -Month 03 -Day 08
PS C:\> $dl.getType().fullName
PS C:\> $d2=Get-Date -Year 2021 -Month 02 -Day 23
Теперь мы можем вычесть из одной даты другую, определив, например, количество
дней между ними:
PS С:\> ($dl-$d2) .Days

Assignment operators

Along with the simple assignment operator (=), PowerShell supports C-like compound assignment operators (Table 8.2).

In the table 8.2 For each compound assignment operator, its analogue is specified, which is composed using a regular assignment operator and a certain arithmetic operator. It is worth considering that all the rules and restrictions described in the previous section apply here for arithmetic operators. For example, the operator += can be applied not only to numbers, but also to strings:

PS С:\> $а = "аа"
PS С:\> $а += "ЬЬ"
PS С:\> $а

An important feature of the assignment operator in PowerShell is that it can be used to assign values to several variables at once with a single command. In this case, the first element of the assigned value will be assigned to the first variable, the second element to the second variable, the third element to the third variable, and so on. For example, the following command will set the variable $a to 1 and the variable $b to 2:

PS С:\> $а, $b = 1, 2
PS С:\> $а
PS С:\> $Ь

If the assigned value contains more elements than the specified variables, the remaining values will be assigned to the last variable. For example, after executing the following command, the value of the variable $a will be the number 1, and the value of the variable $b will be an array of numbers 2 and 3:

PS С:\> $а, $b = 1, 2, 3
PS С:\> $а
PS С:\> $Ь
PS С: \> $Ь. igetType () . fullName

Comparison operators

Comparison operators allow you to compare parameter values in commands. For each comparison operation, a condition is created, which, depending on whether the operator is true or not, takes either the value True or the value Fa1se. PowerShell supports multiple comparison operators, with case-sensitive and case-insensitive versions defined for each operator. The main comparison operators are given in table. 8.3.

The base version of the comparison operators (-eq, -pe, -lt, and so on) are case-insensitive by default. If the operator begins with the letter c (-ceq, -spe, -c1t, etc.), then the comparison will take into account the case of the letters. If the operator starts with a letter (-ieq, -ine, -i1t, and so on), the comparison is case-insensitive.

NOTE PowerShell does not use the regular > and < characters to denote comparison operators because they are reserved for redirecting I/O.

As in the case of arithmetic operators, the “left-hand rule” applies to comparison operators (the type of the left operand is decisive). If a number is compared to a string (the number is to the left of the comparison operator), the string is converted to a number and the two numbers are compared. If the left operand is a string, the right operand is converted to a character type and the two strings are compared.

Let’s look at some examples:

Сравнение числа с числом:
PS С:\> 01 -eq 001
Сравнение числа со строкой (строка ”001” преобразуется в число 1):
PS С:\> 01 -eq "001"
Сравнение строки с числом (число 001 преобразуется в строку "001”):
PS С:\> "01" -eq 001

Comparison using arrays

In PowerShell, you can compare an array to a number, and the result is not a boolean True or Fa1se, but a new array that contains the elements that passed the comparison.


PS С:\> 1,2,3,4,1,2,3 -eq 1
PS С:\> 1,2,3,4,1,2,3 -ge 3
Если тест на сравнение не пройдет ни один элемент, то результатом будет пустой
Для того чтобы узнать, есть ли в массиве элементы, равные указанному значению,
можно воспользоваться оператором -contains, в этом случае результатом будет
True ИЛИ False:
PS С:\> 1, 2, 3, 4 -contains 3
PS С:\> 1, 2, 3, 4 -contains 5

Pattern checking operators

In addition to the basic comparison operators, PowerShell also includes operators that test character strings against a specific pattern. Two types of patterns are supported: regular expressions and regular expressions.

Substitution patterns

Previously, we used wildcards (* and ? ) when using, say, the dir cmdlet. For example, the command dir * .doc displays all files in the current• directory that have the extension .doc and any name (the wildcard * replaces any number of any characters). PowerShell supports four types of wildcards (Table 8.4) and several operators that check strings for wildcard patterns (Table 8.5).

As you can see, using wildcard patterns is very easy, but the capabilities of wildcard patterns are limited. If there is a need to check more complex conditions, then you need to use templates with regular expressions.

Patterns with regular expressions

Regular expressions generalize and extend the concept of generalizing patterns. Literals and metacharacters are used to define a pattern. Every character that has no special meaning in regular expressions is treated as a literal and must be matched exactly when searching. For example, letters and numbers are letter symbols. Metacharacters -t – characters with a special meaning in regular expressions (Table 8.6).

NOTE Regular expression support in PowerShell is implemented using special classes in the .NET framework. The regular expression language supported by these classes is very powerful, but it is beyond the scope of this book to discuss these issues in detail. For more information on some aspects of regular expressions, see in PowerShell’s built-in help (Get—He1p on regu1ar expression).

In PowerShell, the -match and -rep1ace operators work with regular expressions (Table 8.7).

Logical operators

Sometimes it is necessary to check several conditions at once within the framework of one statement. Comparison operators can be connected with each other using the logical operators listed in the table. 8.8 When you use a logical operator, PowerShell checks each condition separately and then evaluates the value of the entire operator by linking the conditions using logical operators.

PowerShell language control instructions

PowerShell, like any other algorithmic language, has elements that allow you to perform a logical comparison and perform different actions depending on its result, or that allow you to repeat one or more commands over and over again.

The If… Elseif… Else statement

Logical comparisons are at the heart of almost all algorithmic programming languages. In PowerShell, the If statement can be used to execute certain blocks of code only if the specified condition is set to True. You can also set one or more additional execution conditions if all previous conditions have been set to Fa1se (false). Finally, you can specify an additional block of code that will be executed if none of the conditions is set to True.

The syntax of the If statement is usually as follows:

if (условие1)
[elseif (условие2)
При выполнении инструкции if проверяется истинность условного выражения

NOTE The most common way to construct conditional expressions in PowerShell is to use the comparison and Boolean operators discussed earlier. In addition, an important feature of the language is that PowerShell command pipelines can be used as conditional expressions.

If the condition! is True, THEN code1 block is executed, and then PowerShell terminates the if statement. If the condition! is False, then PowerShell checks the conditional expression condition2 is true. If condition2 is True, the ‘code2’ block is executed, after which PowerShell completes the if statement. If both condition1 and condition2 are False, then the ‘code_block’ is executed, and then PowerShell completes the if statement. We will give an example of using the if instruction in interactive mode.

Let’s write the number 10 in the $a variable:

PS С:\> $а=10
Сравним теперь значение переменной $а с числом 15:
PS С:\> if ($а -eq 15) {
» 'Значение $а равно 15'
» )
>> else {'Значение $а не равно 15'}
Значение $а не равно 15

This example also shows that you can interactively execute multi-line statements in PowerShell (which can be useful when debugging scripts).

During the cycle

PowerShell supports several types of loops. The simplest of them is the while loop, in which commands are executed until the condition being tested is True. The while statement has the following syntax: while {condition){command_block} When executing a while statement, PowerShell evaluates the condition section of the statement before proceeding to the command_block section. The condition in the instruction takes the value True or False. As long as the condition is True, PowerShell repeats the command_block section.

Remarks As with the if statement, the conditional expression of a while loop can use the PowerShell command pipeline.

The _command block section of the while statement contains one or more commands that are executed each time the loop is entered and repeated. For example, the following while statement displays the numbers 1 through 3 if the variable $vai has not been created or has been created and initialized to 0:

PS С:\> while($val -ne 3)
» {
» $val++
» $val
» }

In this example, the condition ($vai is not equal to 3) is True as long as $vai is 0, 1, or 2. At each iteration of the loop, $vai is incremented by 1 using the unary increment operator ++ ($vai++ ). On the last execution of the loop, the value of $vai becomes 3. In this case, the condition being tested becomes False and the loop terminates.

Do… While loop

Цикл Do ... while похож на цикл while, однако условие в нем проверяется не до
блока команд, а после:
do{блок_команд}while (условие)
PS С:\> $val=O
PS С:\> do {$val++; $val) while ($val -ne 3)

The For loop

The For statement in PowerShell implements another type of loop, the counter loop. Typically, a For loop is used to iterate through an array of values and perform operations on a subset of those values. In PowerShell, the For statement is not used as often as in other programming languages, because collections of objects are usually more convenient to handle with the Forach statement. However, if you need to know which element of a collection or array we’re working with in a given iteration, the For loop can help.

Syntax of the For operator:

for (condition, condition, repeat) command block)

The components of the For loop have the following meaning:

  • Initialization is one or more commands, separated by commas, that are executed before the loop begins. This part of the loop is typically used to create and assign an initial value to a variable, which will then be the basis for testing the condition in the next part of the For statement;

  • A condition is a part of a For statement that can take a Boolean value of True or FaIse. PowerShell evaluates the condition each time the For function is executed. If the result of this evaluation is True, then the commands in the command block block are executed, and then the statement condition is evaluated again. If the condition evaluates to True again, the instructions in the instruction block are executed again, and so on, until the condition test results in Fa1se;

  • A movement is one or more commands, separated by commas, that are executed each time the loop repeats. This part of the loop is usually used to change the variable being tested inside the condition;

  • A command block is a set of one or more commands that are executed when entering a loop or repeating a loop. The contents of the command block are enclosed in curly braces.

A classic example:

PS С:\> for ($i = 0; $i -It 5; $i++) { $i }

Foreach loop

The Foreach operator allows you to sequentially iterate through the elements of collections. The simplest and most commonly used type of collection to move around is an array. As a rule, in the Foreach loop, one or more commands are executed for each element of the array.

The peculiarity of the Foreach loop is that its syntax and operation depend on whether the Foreach statement is outside the command pipeline or inside the pipeline.

A Foreach statement from the command pipeline

In this case, the syntax of the Foreach loop is as follows: foreach ($element in $collection) command block)

Brackets indicate the collection you are browsing. When you execute a Forach loop, the system automatically creates a $element variable. Before each iteration in the loop, this variable is assigned the value of the next element in the collection. The Command Block section contains the commands that are executed for each element of the collection.

For example, the Foreach loop in the following example displays the values in an array named $1etterArray:

PS С:\> $letterArray = "а","b","с","d"
PS С:\> foreach ($letter in $letterArray) {Write-Host $letter}

In the first command here, an array $1etterArray is created, in which four elements are written: the characters a, b, c and d. The first time the Foreach statement is executed, the variable $1etter is set to the value equal to the first element in $letterArray (a), and then the Write-Host cmdlet is used to display the variable $1etter. On the next iteration of the loop, the $1etter variable is assigned the value b, and so on. After all the elements of the $1etterArray array have been iterated, the loop will exit.

The Foreach statement can also be used with cmdlets that return collections of elements.


PS С:\> $п = 0; foreach ($f in dir *.txt) { $n += $f.length }
PS C:\> $n

Here, the $n variable is first created and set to zero, and then in a Foreach loop, a collection of .txt files in the current directory is generated using the dir cmdlet. In a Foreach statement, you loop through all the elements in that collection, and at each step you can access the current element (the corresponding file) using the $f variable. In the command block of the Foreach loop, the value of the 1ength (file size) field of the $f variable is added to the current value of the $p variable. As a result of this loop, the $n variable will store the total size of files in the current directory that have a .txt extension.

Foreach statement inside the command pipeline

If the Foreach statement appears inside the command pipeline, PowerShell interprets it as an alias for Forach, which corresponds to the ForEach-Object cmdlet. So in this case the ForEach-Obj ect cmdlet is actually executed and you no longer need to specify the $element part of the $CALL statement because the elements in the collection are given to the command block by the previous command in the pipeline. The syntax of the Forach statement used inside the command pipeline is, in its simplest form, as follows: command foreach { command block)

An example of calculating the total size of text files from the current directory for this version of the Foreach statement would look like this:

PS С:\> $п = 0; dir *.txt | foreach { $n += length }
PS C:\> $n

In general, the Foreach alias can specify not one command block, but three: start, main, and end command blocks. The start and end blocks of commands are executed once, and the main block is run each time it traverses the collection or array.

The syntax of the Forach alias used in a command pipeline with start, master, and end blocks is as follows:

команда | foreach {начальный_блок_команд} {основной_блок_команд}
Для этого варианта инструкции Foreach наш пример можно записать следующим
PS С:\> dir *.txt | foreach ($n = 0}{ $n += $_.length } {Write-Host $n)

Performance considerations

Therefore, you can solve the problem of iterating through the elements of the collection either by using the Forach loop statement or by processing the objects in the pipeline using the ForEach-Object cmdlet.

When choosing which of these approaches to use, the following point should be kept in mind. The block of code in the ForEach-Object cmdlet starts executing as soon as the first object appears in the pipeline, and the body of the foreach ( ) loop requires that all objects have been fetched and the collection is fully formed. Therefore, you need less RAM when using the ForEach-Object cmdlet (you don’t need to store a whole collection of objects in memory). However, if you massively iterate through the objects of the ready-made collection using foreach (), internal optimizations will work and the processing time for all elements will be much less than if you run the code for each element in the container.

Therefore, the choice of how to process a collection of objects depends on which characteristic is more important to us: RAM consumption or the speed of the task.

Loop labels, break and continuation statements

The Break operator allows you to exit any type of loop without waiting for the end of its iterations. Let’s look at a simple example:

PS С:\> $i=0; while ($true) {if ($i++ -ge 3) { break } $i }

The condition of the whi1e loop in this case is the boolean constant $true, so this loop will never end. The Break statement, which fires when the variable $i reaches the value 3, allows you to exit this loop.

The Continue statement moves to the next iteration of any type of loop. Example:

PS С:\> for ($i=0; $i -le 5; $i++) { if ($i -ge 4) { continue } $i }

In this example, only the number 0 to Z is displayed, because the Continue statement fires for values of the variable $i greater than or equal to 4.

PowerShell supports the ability to immediately exit or go to the next iteration not only for a single loop, but also for nested loops. For this, cycles are assigned special labels, which are indicated at the beginning of the line before the keyword that defines a cycle of a certain type. These labels can then be used in nested loops in conjunction with the Break or Continu statements, indicating which loop the statements should apply to.

Let’s look at a simple example:

PS С:\> :outer while ( $true ) {
» while ( $true ) {
» break outer
» }
» }

Here, the Break statement exits the outer loop marked outer. If the label was not specified, the outer loop would never end.

Switching instructions

The Switch statement, which combines multiple condition checks within a single construct, is available in many programming languages.

However, in PowerShell, this statement has powerful additional capabilities:

  • Can be used as an analogue of a loop, checking the value of an entire array rather than a single element;

  • Can check elements for pattern matching or regular expressions;

  • Can process text files using strings from files as elements to be checked.

Types of checks inside the switch

First, let’s look at the simplest form of the Switch statement, where one scalar expression is matched against several conditions in turn.


PS С:\> $а = 3
PS С:\> switch ($а) {
1 {"Один”}
2 {’’Два"}
3 {"Три"}
4 {"Четыре"}
» }

In this example, the value of the $a variable is sequentially compared to the numbers 1, 2, 3, and 4. If there is a match, the corresponding block of code specified by curly brackets is executed (in our case, a string is simply displayed).

If multiple conditions from the list are true for the value being checked, then all actions matched to those conditions will be performed.


PS С:\> $а = 3
PS С:\> switch ($а) {
>> 1 ("Один"}
>> 2 {"Два"}
>> 3 {"Три"}
» 4 {"Четыре"}
» 3 {"Еще раз три"}
» }
Еще раз три
Если нужно ограничиться только первым совпадением, то следует применить инструкцию Break:
PS С:\> $а = 3
PS С:\> switch ($а) {
» 1 {"Один"}
» }
2 {"Два"}
3 {"Три"; break}
4 {"Четыре"}
3 {"Еще раз три"}
В данном случае проверка условий внутри switch прерывается после нахождения первого соответствия. Если ни одно соответствие не найдено, то инструкция Switch не выполняет никаких действий:
PS С:\> switch (3) {
» 1 {"Один"}
» 2 {"Два"}
>> 4 {"Четыре"}
» }
PS С:\>
С помощью ключевого слова default можно задать действие по умолчанию, которое будет выполняться в том случае, когда не найдено ни одного соответствия. Например:
PS С:\> switch (3) {
>> 1 {"Один"}
» 2 {"Два"}
168 Часть II. PowerShell как язык программирования
» default {"Ни один, ни два")
» }
Ни один, ни два

By default, the Switch statement is compared directly to the objects specified in the condition.

In this case, strings are case-insensitive, for example:

PS С:\> switch ('абв') {
» 'абв' {"Первое совпадение"}
» 'АБВ' {"Второе совпадение"}
» }
Первое совпадение
Второе совпадение
Если при сравнении следует учесть регистр символов, то нужно указать параметр -
PS С:\> switch -casesensitive ('абв') {
» 'абв' {"Первое совпадение"}
» ’ЛЕВ' {"Второе совпадение"}
» }
Первое совпадение
Кроме обычного сравнения может проверять элементы на соответствие шаблону
с подстановочными символами. Для этого используется переключатель -wildcard,
PS С:\> switch -wildcard ('абв') {
» 'а*' {"Начинается с а"}
>> '*в' {"Оканчивается на в"}
» }
Начинается с а
Оканчивается на в
Проверяемый элемент (объект) доступен внутри инструкции switch через специальную переменную $_ (напомним, что в переменной с таким названием сохраняется и текущий элемент, передаваемый по конвейеру от одного командлета другому).
PS С:\> switch -wildcard ('абв') {
» 'а*' {"$_ начинается с а"}
» '*в' {"$_ оканчивается на в"}
» }
абв начинается с а
абв оканчивается на в

As you can see, the $ variable in the double-quoted string is replaced by the string corresponding to the value being checked. The -regex switch allows you to check elements against a pattern that contains regular expressions (issues related to regular expressions were discussed earlier in this section).

For example, the previous example can be written as follows:

PS С:\> switch -regex ('абв') {
» 'Аа’ {"$_ начинается с а"}
» 'в$' {"$_ оканчивается на в"}
» }
абв начинается с а
абв оканчивается на в

In addition to simple match or pattern matching checks, the Switch statement allows you to perform more complex checks by specifying blocks of PowerShell code instead of patterns. In this case, the value being checked is again available via the $ variable.

Let’s consider an example:

PS С:\> switch (10) {
» {$_ -gt 5} {"$_ больше 5")
» {$_ -It 20} {”$_ меньше 20"}
» 10 {"$_ равно 10"}
» }
10 больше 5
10 меньше 20
10 равно 10

At the same time, all three conditions are fulfilled: the values of the first two expressions -gt 5″ and -1t 20″ have the value True, the third condition is the usual comparison of two numbers for equality (10 equals 10).

Validating an array of values

So far, all the values we’ve tested in the Switch statement have been scalar values. The PowerShell language allows you to use arrays of elements as the value to be checked, and the arrays can be specified either explicitly or obtained as a result of executing a command or reading lines from a text file.

Let’s consider an example:

PS С:\> switch (1,2,3,4,5,6) {
» {$_ % 3} {"$_ не делится на три"}
» default {"$_ делится на чри"}
» }
1 не делится на три
2 не делится на три
3 делится на три
4 не делится на три
5 не делится на три
6 делится на три

In this case, the array of integers is given by an explicit enumeration of its elements. All elements of the array are checked one by one inside the Switch statement: if the remainder from dividing the current element by 3 is not equal to zero, then the message “$ is not divisible by three” is displayed, where the value substituted for $_ is checked as usual. Otherwise, the message “$ is divisible by three” is displayed

Here’s another example where the array of items to check is the result of a PowerShell command. Let’s find out the number of files with txt and log extensions located in the Windows system directory. First reset the counter variables:

PS С:\> $txt = $1од = О

Now let’s execute the corresponding Switch instruction. We get a collection of files from the Windows system directory using the command dir $env: SystemRoot (recall that the path to the desired directory is stored in the SystemRoot environment variable). Files with txt and log extensions will be selected by checking for wildcard patterns .txt and *.log respectively) and in the corresponding code blocks we will increment the values of the $txt and $1od variables:

PS С:\> switch -wildcard (dir $env:SystemRoot) {
» *.txt ($txt++)
>> *.log {$log++}
» }
Выведем теперь значения переменных $txt и $iog:
PS C:\> "txt-файлы: $txt log-файлы: $log"
txt-файлы: 21 log-файлы: 156

To use lines from a specific text file as an input array, you need to specify the -fi1e option and the path to the desired file in the Switch statement. Let’s look at an example. Suppose, in the Windows system directory there is a file kB946627.log with the installation protocol of the next update of the operating system. Use the Switch statement to print all lines from this file that contain the substrings “Source:” or “Destination:” (using the -wi1dcard and -fi1e options, the lines from the file are checked against the generalization pattern):

PS С:\> switch -widlcard -file $env:SystemRoot\KB946627.log {
>> *Source:* {$_}
>> *Destination:* {$_}
» }
10.281: Source:C:\WINDOWS\system32\SET32.tmp (5.1.2600.3173)
10.281: Destination:С:\WINDOWS\system32\rpcrt4.dll (5.1.2600.2180)
10.281: Source:C:\WINDOWS\system32\SETDB.tmp (5.1.2600.3243)
10.281: Destination^:\WINDOWS\system32\xpsp3res.dll (5.1.2600.3132)
10.281: Source:C:\WINDOWS\system32\SET9E.tmp (6.0.2900.3231)
10.281: Destination:^\WINDOWS\system32\wininet.dll (6.0.2900.3132)
10.281: Source:C:\WINDOWS\system32\SET9F.tmp (6.0.2900.3231)
10.281: Destination:C:\WINDOWS\system32\urlmon.dll (6.0.2900.3132)


  • PowerShell operators are polymorphic, and the same operator can be applied to different types of objects.

  • The behavior of most binary operators is determined by the “left-handed rule”. The type of the operand on the left indicates the type of the result of the operator.

  • PowerShell supports C-like compound assignment statements.

  • Comparison operators are specified in PowerShell using character abbreviations, the < and > characters are not used.

  • Two variants of string validation operators are supported: pattern wildcards and regular expressions.

  • PowerShell supports standard control statements for branching and looping.

  • The Switch statement in PowerShell has more capabilities than similar constructs in other programming languages. With one switch, without an additional loop, you can check the elements of an array or string from a text file for matching a pattern.

  • You can process collections of objects using loops or pipelines. Loops tend to consume more memory, but operations are performed faster than pipelines.

Thanks to our team of volunteers for providing information from open sources.

Other related articles
Found an error?
If you find an error, take a screenshot and send it to the bot.