What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Historically, command-line utilities on Unix systems are better developed than on Windows, but with the advent of a new solution, the situation has changed.

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

PowerShell can be scripted in an interpreted, multi-paradigm language that has elements of classic procedural, object-oriented, and even functional programming: conditional branching, loops, variables, arrays, hash tables, classes, error handling, as well as functions, cmdlets, and pipelines . Previous article was devoted to the basics of working in the environment, and now we offer readers a small guide for programmers.

Table of Contents:

Comments
Variables and their types
System variables
Scopes
Environment variables (environment)
Arithmetic and comparison operators
Assignment operators
Logical operators
Conditional Jump
Cycles
Arrays
Hash tables
Functions
Error processing

You can write code in any text editor or using an integrated development environment - the easiest way is to take the Windows PowerShell ISE that comes with Microsoft server operating systems. This is only necessary for fairly complex scripts: short sets of commands are easier to execute interactively.

Comments

Using comments is considered part of good programming style along with proper indentation and whitespace:

# Для строчных комментариев используется символ решетки — содержимое строки интерпретатор не обрабатывает.

<# 

       Так обозначаются начало и конец блочного комментария. 
       Заключенный между ними текст интерпретатор игнорирует.

#>

Variables and their types

Variables in PowerShell are named objects. Their names can include the underscore character, as well as letters and numbers. The $ symbol is always used before the name, and to declare a variable, it is enough to give the interpreter a valid name:

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

To initialize a variable (assign a value to it), the assignment operator (symbol =) is used:

$test = 100

You can declare a variable by specifying its type in square brackets (type casting operator) before the name or value:

[int]$test = 100

$test = [int]100

It is important to understand that variables in PowerShell are full-fledged objects (classes) with properties and methods whose types are based on those in .NET Core. We list the main ones:

Type (.NET class)

Description

Sample code

[string] System.String

Unicode string 

$test = "test"
$test = 'test'

[char]System.Char

Unicode character (16 bits)

[char]$test = 'c'

[bool] System.Boolean

boolean type (boolean True or False)

[bool]$test = $true

[int] System.Int32

thirty-two bit integer (32 bits)

[int]$test = 123456789

[long] System.Int64

sixty-four bit integer (64 bits)

[long]$test = 12345678910

[single] System.Single

floating point number 32 bits long

[single]$test = 12345.6789

[double]System.Double

floating point number of length 64 bits (8 bytes)

[double]$test = 123456789.101112

[decimal]System.Decimal

128-bit floating point number (required to end with d)

[decimal]$test = 12345.6789d

[DateTime]System.DateTime

date and time 

$test = GetDate

[array] System.Object[]

an array whose element index starts at 0

$test_array = 1, 2, "test", 3, 4

[hashtable] System.Collections.Hashtable

hash tables are associative arrays with named keys, built according to the principle: @{key = "value"}

$test_hashtable = @{one="one"; two="two"; three="three"}

PowerShell supports implicit type conversion, in addition, the type of a variable can be changed on the fly (for example, using an assignment operator), if it is not specified forcibly - in this case, the interpreter will give an error. You can determine the type of the variable from the previous example by calling the GetType() method:

$test.GetType().FullName

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

There are a number of cmdlets for manipulating variables. Their list in a convenient form is displayed using the command:

Get-Command -Noun Variable | ft -Property Name, Definition -AutoSize -Wrap

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

To view declared variables and their values, you can use a special cmdlet:

Get-Variable | more

This method seems overly cumbersome, it is much more convenient to work with variables through operators or by accessing their properties and methods directly. However, cmdlets have a right to exist because they allow you to set some additional parameters. It is important to understand that user variables are only defined within the current session. When the console is closed or the script ends, they are deleted.

System variables

In addition to those declared by the user, there are built-in (system) variables that are not deleted after the current session ends. They are divided into two types, while PowerShell state data is stored in automatic variables that cannot be assigned arbitrary values ​​on their own. These include, for example, $PWD:

$PWD.Path

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Preference variables are needed to store user preferences, the values ​​of which can be changed. For example, using $ErrorActionPreference , the reaction of the command interpreter to the occurrence of non-fatal errors is set.

In addition to operators and cmdlets for accessing declared variables, there is a Variable: pseudo-accumulator. You can work with it by analogy with other drives, and the variables in this case resemble file system objects:

Get-ChildItem Variable: | more

or

ls Variable: | more

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Scopes

For variables in PowerShell, there is the concept of scope (Scope). The action of the global scope (Global) applies to the entire current session - it includes, for example, system variables. Local (Local) variables are available only in the scope where they were defined: say inside a function. There is also the concept of the scope of the script (Script), but for script commands, it is essentially local. By default, when declaring variables, they are given a local scope, and to change this, you need a special construct like: $Global: variable = value.

For example, this:

$Global:test = 100

Environment variables (environment)

Another pseudo-drive, Env:, is available from PowerShell and can be used to access environment variables. When the shell starts, they are copied from the parent process (that is, from the program that initiated the current session) and usually their initial values ​​are the same as the values ​​in the control panel. To view environment variables, use the Get-ChildItem cmdlet or its aliases (aliases): ls and dir.

dir Env:

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

These variables are sequences of bytes (or characters, if you like), the interpretation of which depends only on the program using them. The *-Variable cmdlets don't work with environment variables. To access them, you have to use the drive prefix:

$env:TEST = "Hello, World!"

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Arithmetic and comparison operators

PowerShell provides the following arithmetic operators: + (addition), - (subtraction), * (multiply), / (division), and % (modulo or modulo). The result of an arithmetic expression is evaluated from left to right in accordance with the generally accepted order of operations, and parentheses are used to group parts of the expression. Spaces between operators are ignored, they are used only to make it easier to read. The + operator also concatenates, and the * operator repeats strings. If you try to add a number to a string, it will be converted to a string. In addition, the PowerShell language has many comparison operators that check for a match between two values ​​and return the boolean True or False:

Operator

Description

Sample code

-eq

Equal / Equals (similar to = or == in other languages)

$test = 100
$test -eq 123 

-born

Not equal / Not equal (similar to <> or !=)

$test = 100
$test -ne 123   

-gt

Greater than / More (analogue>)

$test = 100
$test -gt 123

-give

Greater than or equal / Greater than or equal (similar to >=)

$test = 100
$test -ge 123

-according to

Less than / Less (similar to <)

$test = 100
$test -lt 123  

-Le

Less than or equal / Less than or equal (similar to <=)

$test = 100
$test -le 123

There are other similar operators that allow you to, for example, compare strings based on a wildcard or use regular expressions to match a pattern. We will cover them in detail in future articles. The symbols <, > and = are not used for comparison because they are used for other purposes.

Assignment operators

In addition to the most common = operator, there are other assignment operators: +=, -=, *=, /= and %=. They change the value before assignment. The unary operators ++ and -, which increase or decrease the value of a variable, behave similarly - they also apply to assignment operators.

Logical operators

Comparison alone is not enough to describe complex conditions. You can write any logical expressions using the operators: -and, -or, -xor, -not and! .. They work like in other programming languages, while you can use parentheses to specify the order of evaluation:

("Тест" -eq "Тест") -and (100 -eq 100)

-not (123 -gt 321) 

!(123 -gt 321)

Conditional Jump

Branch operators in PowerShell are standard: IF(IF…ELSE, IF…ELSEIF…ELSE) and SWITCH. Let's look at their use with examples:

[int]$test = 100
if ($test -eq 100) {
      Write-Host "test = 100"
}



[int]$test = 50
if ($test -eq 100) {
       Write-Host "test = 100"
}
else {
      Write-Host "test <> 100"
}



[int]$test = 10
if ($test -eq 100) {
      Write-Host "test = 100"
}
elseif ($test -gt 100) {
      Write-Host "test > 100"
}
else {
       Write-Host "test < 100"
}



[int]$test = 5
switch ($test) {
     0 {Write-Host "test = 0"}
     1 {Write-Host "test = 1"}
     2 {Write-Host "test = 2"}
     3 {Write-Host "test = 3"}
     4 {Write-Host "test = 4"}
     5 {Write-Host "test = 5"}
     default {Write-Host "test > 5 или значение не определено"}
}

Cycles

PowerShell has several varieties of loops: WHILE, DO WHILE, DO UNTIL, FOR, and FOREACH.

A loop with a precondition works if/as long as it is true:

[int]$test = 0
while ($test -lt 10) {
      Write-Host $test
      $test = $test + 1
}

Loops with a postcondition will run at least once, because the condition is checked after the iteration. At the same time, DO WHILE works while the condition is true, and DO UNTIL works while it is false:

[int]$test = 0
do {
      Write-Host $test
      $test = $test + 1 
}
while ($test -lt 10)



[int]$test = 0
do {
      Write-Host $test
      $test = $test + 1 
}
until ($test -gt 9)

The number of iterations of the FOR loop is known in advance:

for ([int]$test = 0; $test -lt 10; $test++) {
       Write-Host $test
}

In the FOREACH loop, iterates over the elements of an array or collection (hash table):

$test_collection = "item1", "item2", "item3"
foreach ($item in $test_collection)
{
        Write-Host $item
}

Arrays

PowerShell variables store not only single objects (number, string, etc.), but also multiple ones. The simplest kind of such variables are arrays. An array can consist of several elements, one element, or be empty, i.e. contain no elements. It is declared using the @() operator, which we will need in the next article - it is very important for adding other arrays to an array (creating multidimensional arrays), passing arrays to functions as an argument, and similar tasks:

$test_array = @() #создаем пустой массив

When an array is initialized, its values ​​are listed separated by commas (special operator ,):

$test_array = @(1, 2, 3, 4) # создаем массив из четырех элементов 

In most cases, the @() operator can be omitted:

$test_array = 1, 2, 3, 4

In this case, an array of one element is initialized as follows

$test_array = , 1

Array elements are accessed using a zero-based integer index and the index operator (square brackets):

$test_array[0] = 1

You can specify several indexes separated by commas, incl. recurring:

$test_array = "один", "два", "три", "четыре"
$test_array[0,1,2,3]
$test_array[1,1,3,3,0]

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Operator .. (two dots - range operator) returns an array of integers within the specified upper and lower bounds. For example, expression 1..4 outputs an array of four elements @(1, 2, 3, 4), and expression 8..5 outputs an array @(8, 7, 6, 5).

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Using the range operator, you can initialize an array ($test_array = 1..4) or get a slice (slice), i.e. a sequence of elements from one array with indices from another. In this case, a negative number -1 denotes the last element of the array, -2 - the penultimate one, and so on.

$test_array = "один", "два", "три", "четыре"
$test_array[0..2]
$test_array[2..0]
$test_array[-1..0]
$test_array[-2..1]

Note that integer array values ​​can be greater than the maximum index value of the data array. In this case, all values ​​are returned up to the last one:

$test_array[0..100]

If you try to access a single non-existent array element, $null is returned.

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

In PowerShell, arrays can contain elements of different types or be strongly typed:

$test_array = 1, 2, "тест", 3, 4
for ([int]$i = 0; $i -lt $test_array.count; $i++)
{
          Write-Host $test_array[$i]
}

Where the $test_array.count property is the number of array elements.

An example of creating a strongly typed array:

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

Hash tables

Another basic type of variables in the PowerShell language are hash tables, also known as associative arrays. Hashtables are similar to JSON objects and are built on a key-value basis. Unlike ordinary arrays, their elements are accessed by named keys, which are properties of the object (you can also use the index operator - square brackets).

An empty hash table is declared using the @ symbol and operator brackets:

$test_hashtable = @{}

When declaring, you can immediately create keys and assign values ​​to them:

$test_hashtable = @{one="один"; two="два"; three="три"; "some key"="some value"}

To add an element to a hash table, you must assign a key that does not yet exist to it, or use the Add () method. If an assignment is made to an existing key, its value will change. The Remove() method is used to remove an element from a hash table.

$test_hashtable."some key"
$test_hashtable["some key"]
$test_hashtable.Add("four", "четыре")
$test_hashtable.five = "пять"
$test_hashtable['five'] = "заменяем значение"
$test_hashtable.Remove("one")

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Variables of this type can be passed as arguments to functions and cmdlets - in the next article we will study how this is done, and also consider another similar type - PSCustomObject.

Functions

PowerShell has everything you need for procedural programming, including functions. To describe them, the function word Function is used, after which you need to specify the name of the function and the body enclosed in operator brackets. If you need to pass arguments to the function, you can specify them immediately after the name in parentheses.

function имя-функции (аргумент1, ..., аргументN) 
{ 
        тело-функции 
} 

The function always returns a result - it is an array of the results of all its statements, if there are more than one. If there is only one statement, the only value of the corresponding type is returned. The return $value construct adds an element with the value $value to the result array and aborts the execution of the statement list, and the empty function returns $null.

For example, let's create a function for squaring a number:

function sqr ($number)
{
      return $number * $number
}

Note that in the body of a function, you can use any variables declared before calling it, and calling functions in PowerShell may seem unusual: the arguments (if any) are not enclosed in parentheses and are separated by spaces.

sqr 2

Or so:

sqr -number 2

Because of the way arguments are passed, the function itself sometimes needs to be enclosed in parentheses:

function test_func ($n) {}
test_func -eq $null     # функция не вызывалась
(test_func) -eq $null   # результат выражения — $true

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

When describing a function, you can assign default values ​​to arguments:

function func ($arg = value) {
         #тело функции
}

There is another syntax for describing function arguments, in addition, parameters can be read from the pipeline - all this will come in handy in the next article, when we look at exported modules and creating our own cmdlets.

Error processing

PowerShell has a Try...Catch...Finally mechanism to handle exceptions. The Try block contains the code in which an error may occur, and the Catch block contains its handler. If there was no error, it is not executed. The Finally block is executed after the Try block, regardless of the occurrence of an error, and there can be several Catch blocks for different types of exceptions. The exception itself is written to an undeclared default variable ($_) and can be retrieved easily. In the example below, we implement protection against entering an invalid value:

try {

        [int]$test = Read-Host "Введите число"
        100 / $test

} catch {

         Write-Warning "Некорректное число"
         Write-Host $_

}

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

This concludes the review of the basics of programming in the PowerShell language. In the following articles, we will study in more detail working with variables of different types, collections, regular expressions, creating functions, modules and custom cmdlets, as well as object-oriented programming.

What is Windows PowerShell and what is it eaten with? Part 2: Introduction to the programming language

Source: habr.com

Add a comment