Part 7. PowerShell as a programming language (Variables, arrays and hash tables)

26 July 2023 19 minutes Author: Lady Liberty

PowerShell: Variables, Arrays, and Hashtables for Beginners and Pros

PowerShell is a powerful programming language and command shell that is widely used in the field of system administration, automation of routine tasks, and data processing. In our complete guide, we’ll cover the key aspects of working with variables, arrays, and hash tables in PowerShell. Let’s start with the basics – understanding variables in PowerShell and their types. We learn how to create and assign values to variables and how they are used to store different types of data. Next, let’s move on to arrays – data structures that allow you to store several values in one variable. Arrays play an important role in working with lists of data and allow easy iteration and manipulation of elements. We will pay special attention to hash tables – a useful data structure that allows you to store “key-value” pairs.

Let’s learn how to create and use hash tables, their features and advantages. Our guide will introduce you to the basics of working with variables, arrays, and hash tables in PowerShell, help you understand their role in programming and administration, and provide you with the knowledge you need to work effectively with this powerful programming language. In the previously discussed examples, we used various numeric and symbolic literals (constants), and even PowerShell variables, in which we stored the results of executing commands. In addition to PowerShell variables, as in many other programming languages, arrays are supported, as well as more specific structures – associative arrays (hash tables). Let’s consider these elements of the PowerShell language in more detail.

Numeric and symbolic literals

Practically every programming language has the ability to work with numbers and strings of characters, and the methods of their installation can be different (for example, in some languages strings must be enclosed in double quotes, and in others – in single quotes). Tayuke PowerShell supports integers and real numbers, and Tayuke supports several kinds of character strings.

Numeric literals

In PowerShell, variables are .NET Framework objects. All major numeric types of this platform are supported: System. Int32, system. Int64, system. Double 1e. At the same time, there is no need to explicitly set the number type – the system itself selects the appropriate type for the specified number. Let’s check the type of several numbers using the GetType method:

PS С:\> (10).gettype().fullname
System.Int32
PS C:\> (10.23).gettype().fullname
System.Double
PS C:\> (10+10.23).gettype().fullname
System.Double

PowerShell provides special multiplier suffixes to simplify work with values often used by system administrators: kilobytes, megabytes, and gigabytes (Table 7.1).

Here are some examples:

PS С:\> lmb+lOkb
1058816
PS С:\> 2GB+56MB
2206203904

In PowerShell, you can operate on numbers in hexadecimal using the same notation as in C-like programming languages: the number is prefixed with OH, and the numbers and letters A, B, C, D, E, and (case-independent) can be present in the number record. Example:

PS С:\> 0x10
16
PS С:\> ОхА
10
PS С:\> Oxcd
205

Character strings

All character strings in PowerShell are objects of type System. A string is a sequence of 32-bit Unicode characters. The length of the lines is not limited, the contents of the lines cannot be changed (you can only copy them). PowerShell supports four types of character strings.

Lines are single and double quoted

Strings can be defined by a sequence of characters enclosed in single or double quotes:

PS С:\> 'Строка в одинарных кавычках'
Строка в одинарных кавычках
PS С:\> "Строка в двойных кавычках"
Строка в двойных кавычках

Strings can contain any character (including line breaks and carriage returns) except the corresponding single terminating character (single or double quotes). A single-quoted string can contain double quotes and vice versa:

PS С:\> 'Строка в "одинарных" кавычках'
Строка в "одинарных" кавычках
PS С:\> "Строка в 'двойных' кавычках"
Строка в 'двойных' кавычках

If you want to put a character inside a string that delimits that string (ie a single or double quote), then you need to write that character twice in a row:

PS С:\> 'Строка в ''одинарных кавычках'
Строка в 'одинарных кавычках
PS С:\> "Строка в ""двойных кавычках"
Строка в "двойных кавычках

Lines enclosed in double quotes can be expanded. Ego means that if there is a variable name or other expression that can be evaluated inside such a string, then the value of this variable or the result of evaluating the expression is substituted into the string. Example:

PS С:\> $а=123
PS С:\> "$а равно $а"
123 равен 123

If the name of the variable occurs inside the string in single quotes, then the substitution of the value of the variable does not occur:

PS С:\> '$а равно $а'
$а равен $а

Optionally, you can disable the expansion of a specific variable in a double-quoted string. To do this, you need to specify a backslash symbol before the $ sign of this variable, for example:

PS С:\> "$а равно $а"
$а равно 123

Special characters are enclosed in double-quoted lines, which in PowerShell begin with the backslash apostrophe character (Table 7.2).

Let’s insert a line break symbol into a line with double quotes:

PS С:\> "Строка в пдвойных кавычках"
Строка в
двойных кавычках

As you can see, the information is displayed on the screen in two lines. If you insert single quotes into a line, the line break will not occur:

PS С:\> 'Строка в подинарных кавычках'
Строка в 'подинарных кавычках

In addition to variables, expanding lines can contain so-called subexpressions – pieces of PowerShell code delimited by $ characters ( . . . ). Example:

PS С:\> "3+2 равно $(3+2)"
3+2 равно 5

Strings of type here-string

In PowerShell, along with ordinary strings in single and double quotes, so-called here-string strings are supported. Such lines are usually used to insert large blocks of text into a script or when generating text information for other programs and have the following format:

@<quote><line break>text block<line break><quote> @

Quotation marks can be either single or double, and their meaning remains the same as for regular strings: variables and subexpressions inside double quotes are replaced by their values, and those inside single quotes remain unchanged. Example:

PS С:\> $а=@"
» 1 Первая строка
» $(1+1) Вторая строка
» "Третья строка"
» "@
»
PS С:\> $а
1 Первая строка
2 Вторая строка
"Третья строка"
PS С:\> $а=@' » 1 Первая строка
» $(1+1) Вторая строка
» 'Третья строка’
»
»
PS С:\> $а
1 Первая строка
$(1+1) Вторая строка
’Третья строка’

PowerShell variables

Note that the here string delimiter must contain a line break, so various special characters (such as single or double quotes) can be used in such strings without restriction.

As we already know, PowerShell variable names always start with a dollar sign ($). PowerShell variables do not need to be declared or defined in advance, they are created when the variable is first assigned a value. If you try to access a nonexistent variable, the system will return $pi 11.

You can check for a certain variable using the TestPath cmdlet with the PowerShell virtual disk Variab1e: specified. For example, the following command checks whether a variable named MyVariab1e exists:

PS С:\> Test-Path Variable:MyVariabie
False »
Список всех переменных, определенных в текущем сеансе работы, можно увидеть,
обратившись к виртуальному диску variable: с помощью команды dir:
PS С:\> dir Variable:
Name
$
Value
True
args
ConfirmPreference
ConsoleFileName
DebugPreference
Error
ErrorActionPreference
Errorview
{}
High
S ilentlyContinue
{}
Continue
Normalview
Если пользователь не создавал пока своих переменных, то в системе определены
только переменные оболочки PowerShell.

PowerShell shell variables

Shell variables are a set of variables that are created, declared by PowerShell, and present by default in every session. Shell variables persist throughout a session and are available to all commands, scripts, and programs that run in that session. Two types of shell variables are supported:

  • Automatic variables. These variables store PowerShell state settings. Automatic variables are stored and dynamically changed by the system itself. Users cannot (and should not) change the values of these variables. For example, the value of the $PID variable is the ID of the current PowerShell.exe process.

  • Settings variables. These variables store the settings of the active user. These variables are created by PowerShell and populated with default values. Users can change the values of these variables. For example, the variable $MaximumHistoryCount defines the maximum number of entries in the session history.

In the table Figure 7.3 provides a brief description of some shell variables.

Shell variables can be used just like other types of variables. For example, the following command will display the contents of the PowerShell home directory, the path to which is stored in the $PSHome shell variable:

PS С:\Users\andrv> dir $PSHome
Каталог: С:\Windows\System32\WindowsPowerShell\vl.О
Mode LastWriteTime Length Name
d---- 28.09.2020 15:55 en-US
d----- 07.12.2019 12:14 Examples
d---- 28.09.2020 16:13 Modules
d---- 07.12.2019 17:36 ru
d---- 07.12.2019 17:34 ru-RU
d---- 07.12.2019 12:14 Schemas
d---- 07.12.2019 12:14 SessionConfig

Custom variables

A user variable is created the first time it is assigned a value. For example, let’s create an integer variable $a:

PS С:\> $а = 1
PS С:\> $а
1
PS С:\> Test-Path Variable:а
True
PS С:\> dir Variable:а
Name Value
a 1
Типы переменных
Проверим, какой тип имеет переменная $а. Для этого можно воспользоваться командлетом Get-Member ИЛИ методом getType () :
PS С:\> $а | Get-Member
TypeName: System.Int32
PS C:\> Get-Member -Inputobject $a
TypeName: System.Int32
PS C: \> $a. getType () . fullName
System.Int32
Итак, переменная $a сейчас имеет тип System. int32. Присвоим этой переменной
другое значение (строку) и вновь проверим тип:
PS С:\> $а = "ааа"
PS С:\> $а | Get-Member
TypeName: System.String

As you can see, the type of variable $a has changed to System. A string, that is, the type of a variable is determined by the type of the last value assigned to it.

You can also explicitly specify the type of a variable when you define it by specifying the appropriate type attribute in square brackets. In this case, the expression on the right side after the equal sign will be converted (if possible) to this type. For example, let’s declare an integer variable $a and assign this variable a character value that can be converted to an integer type:

PS С:\> [System.Int32]$а = 10
PS С:\> $а = "123"
PS С:\> $а
123
PS С:\> $а.getType().fullName
System.^nt32
Как видим, строка ”123” была преобразована в целое число 123. Если же попытаться записать в переменную $а значение, которое не может быть преобразовано
в целое число, то возникнет ошибка:
PS С:\> $а = "ааа"
Не удается преобразовать значение "ааа" в тип "System.Int32". Ошибка: "Входная
строка имела неверный формат."
строка:1 знак:1
+ $а = "ааа"
+ ------------
+ Categoryinfo : MetadataError: (:) [],
ArgumentTransformationMetadataException
+ FullyQualifiedErrorld : RuntimeException
Вместо явного указания .NET-типа переменной можно пользоваться более краткими псевдонимами типов. Например:
PS С:\> [int]$a = 10
PS С:\> $а.GetType().FullName
System.Int32

The most frequently used type aliases are listed in the table. 7.4.

Typewriting

To explicitly cast a value to a specific type, you must specify the type (either in full .NET type form or as an alias) before the value. For example, let’s store the sum of two numbers in the variable $a:

PS С:\Users\andrv> $а = 100.1 + 9.9
Переменная $а будет числом:
PS С:\Users\andrv> $a.getType().fullName
System.Double
PS C:\Users\andrv> $a
110
Теперь преобразуем при сложении каждое число к символьному типу.
PS С:\Users\andrv> $а = [string]100.1 + [string]9.9
В этом случае переменная $а будет строкой:
PS С:\Users\andrv> $а.getType().fullName
System.String
PS C:\Users\andrv> $a
100.19.9

Additional variable attributes

For variables in PowerShell, you can specify not only their type, but also some additional attributes that limit the set of possible values for these variables. For example, let’s create an integer variable $a with a limited range of values. The va1idateRange attribute is used for this.

PS С:\Users\andrv> [validateRange(1,5)][int]$а = 4
Теперь система не даст записать в эту переменную число, меньшее единицы или
большее пяти:
PS С:\Users\andrv> $а = 6
Не удалось выполнить проверку переменной, т. к. значение 6 является
недопустимым для переменной а.
строка:1 знак:1
+ $а = 6
+ —-- -
+ Categoryinfo : MetadataError: (:) [], ValidationMetadataException
+ FullyQualifiedErrorld : ValidateSetFailure
С помощью атрибута validateLengthO можно ограничить длину символьной переменной. Например:
PS С:\Users\andrv> [validateLength(0,4)][string]$s = 'abed'
В переменную $s нельзя будет сохранить строку длиной более четырех символов:
PS С:\Users\andrv> $s = ’abode'
Не удалось выполнить проверку переменной, т. к. значение abode является
недопустимым для переменной s.
строка:1 знак:1
+ $s = 'abode'
+ Categoryinfo : MetadataError: (:) [], ValidationMetadataException
+ FullyQualifiedErrorld : ValidateSetFailure

Constants

In PowerShell, you can create constants, which are variables whose value cannot be changed. To do this, use the New-Variab1e or Set-Variab1e cmdlet with the parameter -0ption Constant. Example:

PS С:\Users\andrv> New-Variable -Name pi -Value 3.14 -Option Constant
Данная команда создала переменную $pi (обратите внимание, что в атрибуте -Name
знак доллара не указывается) со значением 3,14:
PS С:\Users\andrv> $pi
3.14
Глава 7. Переменные, массивы и хэш-таблицы____________________________________ 137
Попытка изменить значение такой переменной приведет к возникновению ошибки:
PS С:\Users\andrv> $pi = 1
Не удается перезаписать переменную pi, т. к. она является постоянной либо
доступна только для чтения.
строка:1 знак:1
+ $pi = 1
4- --------
+ Categoryinfo : WriteError: (pi:String) [],
SessionStateUnauthorizedAccessException
+ FullyQualifiedErrorld : VariableNotWritable

Windows environment variables

In addition to its own variables, PowerShell also allows you to work with Windows environment variables (or environment variables), each of which is stored in RAM for the duration of the operating system session, has its own unique name, and its value is a string. Standard environment variables are automatically initialized during the boot process of the operating system. Such variables include, for example:

  • WINDIR – the path to the Windows installation directory;

  • TEMP – path to the directory where temporary Windows files are stored;

  • RATN is a system path (search path), that is, a list of directories in which the system should search for executable files or general files (for example, dynamic libraries).

In PowerShell, environment variables can be accessed through the Env: virtual drive. For example, the dir cmdlet lists all environment variables. For example, a list of all environment variables is displayed by the volume dir command:

PS С:\Users\andrv> dir Env:
Name
ALLUSERSPROFILE
APPDATA
Chocolateylnstall
ChocolateyLastPathUpdate
CommonProgramFiles
CommonProgramFiles(x86)
CommonProgramW6432
COMPUTERNAME
Value
C:\ProgramData
C:\Users\andrv\AppData\Roaming
C:\ProgramData\chocolatey
132578680900827918
C:\Program Files\Common Files
C:\Program Files (x86)\Common Files
C:\Program Files\Common Files
DESKTOP-BU86I5T

Arrays in the PowerShell shell

Unlike many programming languages, PowerShell does not require special characters to indicate the start or end of an array or to predeclare an array.

To create and initialize an array, you can simply assign values to its elements. Values added to an array are separated by commas and separated by an assignment operator from the variable name (array name). For example, the following command will create an array $a with three elements:

PS С:\> $а = 1, 2, 3
PS С:\> $а
1
2
3

In the PowerShell shell, parentheses around an expression indicate that the expression should be evaluated. Therefore, the list of array values can be specified in parentheses, which will make arrays more visible in scripts:

PS С:\Users\andrv> $names = ('Иван', 'Сергеи', 'Андреи')
PS С:\Users\andrv> $names
Иван
Сергей
Андрей
Дополнительно перед скобками можно указать знак @:
PS С:\Users\andrv> $numbers = 0(10, 20, 45)
PS С:\Users\andrv> $nurobers
10
20
45
Выражение @ () создаст пустой массив, не содержащий элементов.
PS С:\Users\andrv> $а = @()
PS С:\Users\andrv> $а.getType().fullName
System.Object[]
PS C:\Users\andrv> $a.length
0
При объявлении пустого массива символ @ нужно указывать обязательно, без него
возникнет ошибка:
PS С:\Users\andrv> $а = ()
строка:1 знак:7
+ $а = ()
+
После ’'(’' ожидалось выражение.
+ Categoryinfo : ParserError: (:) [],
ParentContainsErrorRecordException
+ FullyQualifiedErrorld : ExpectedExpression
Можно также создать и инициализировать массив, используя оператор диапазона (..). Например, следующая команда создает массив $ь, содержащий числа от 10
до 14:
PS С:\> $Ь = 10..14
В результате массив $ь будет содержать пять значений:
PS С:\> $Ь
10
11
12
13
14

As we have seen, to display all elements of the array, you just need to enter its name. The length of the array (number of elements) is stored in the Length property:

PS С:\> $а.Length
3
Псевдонимом свойства Length является СВОЙСТВО Count:
PS С:\> $а.Count
3

To access a specific element of the array, you need to specify its serial number (index) in square brackets after the variable name. Keep in mind that the numbering of elements in a PowerShell array is always zero, so to get the value of the first element, you need to run the following command:

PS С:\> $а[0]
1

Negative values can also be specified as an index, and the count will be from the end of the array. For example, the index –l will correspond to the last element of the array:

PS С:\> $а[-1]
3

The PowerShell language allows you to retrieve multiple values from an array at once. To do this, you can use a range operator or another array with integer elements as an array index. For example, you can get elements of the array $a with indexes from I to 2 in different ways:

PS С:\> $а[1..2]
2
3
PS С:\> $а[1, 2]
2
3
PS С:\Users\andrv> $п = 1,2
PS С:\Users\andrv> $а[$п]
2
3

The Length property can be used in a range operator. For example, to display the elements from index I to the end of the array (the last element of the array has index Length-l), you can execute the following command:

PS С:\> $а[1..($а.Length-1)]
2
3
Для изменения элемента массива нужно присвоить новое значение элементу с соответствующим индексом:
PS С:\> $а[0] = 5
PS С:\> $а[1] = 3.14
PS С:\> $а[2]= "привет"
PS С:\> $а
5
3.14
привет

Operations with arrays

The last example shows that by default PowerShell arrays can contain elements of different types, that is, they are polymorphic. Let’s see what type our $a array has:

PS С:\> $а.getType().fullName
System.Object[]

Therefore, the variable $a has the type “array of elements of type System. [ ] “. You can create an array with a hard-coded type, that is, an array that contains elements of only one type. For this, as in the case of ordinary scalar variables, it is necessary to specify the desired type in square brackets before the name of the variable (see Table 6.5). For example, the following command will create an array of 32-bit integers:

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

Increasing the length of the array. Combining arrays

Attempting to access an element that is outside the bounds of the array will result in an error. Example:

PS С:\> $а.Length
4
PS С:\> $а[4] = 5
Индекс находился вне границ массива.
строка:1 знак:1
+ $а[4]=5
+ —-
+ Categoryinfo : OperationStopped: (:) [], IndexOutOfRangeException
+ FullyQualifiedErrorld : System.IndexOutOfRangeException

Such errors are due to the fact that PowerShell arrays are based on . NET arrays that have a fixed length. Despite this, there is a way to increase the length of the array. For this, you can use the union operator + or +=. For example, the following command will add two new elements with the values 5 and 6 to the $a array.

PS С:\> $а
1
2
3
4
PS С:\> $а += 5,6
PS С:\> $а
1
2
3
4
5
6
PS С:\>

When the += operator is executed, the following occurs:

  • PowerShell creates a new array that is large enough to hold all the elements.

  • The original array contents are copied to the new array.

  • New elements are copied to the end of the new array.

Thus, we actually do not add a new element to the array, but create a new array with a larger dimension. You can combine two arrays into one using the + operator. Example:

PS С:\> $х = 1,2
PS С:\> $у = 3,4
PS С:\> $z = $х + $у
PS С:\> $z
1
2
3
4

Deleting items

Removing an element from an array is not that easy, but you can create a new array and copy all the elements except the unnecessary ones into it. For example, the following command will create an array $b that contains all elements of the array $a except for index 2:

PS С:\> $Ь = $а[0,1 + 3..($а.length-1)]
PS С:\> $Ь
1
2
4
5
6

Action of the assignment operator

It should be noted that the usual assignment operator (=) acts on arrays by reference. For example, let’s create an array $a from two elements and assign this array to the variable $b:

PS С:\> $а = 1, 2
PS С:\> $Ь = $а
PS С:\> $Ь
1
2
Теперь изменим значение первого элемента массива $а и посмотрим еще раз на
содержимое массива $ь:
PS С:\> $а[0] = "Новое значение"
PS С:\> $Ь
Новое значение
2
PS С:\>
Как видим, содержимое массива $ь также изменилось, т. к. переменная $ь указывает на тот же объект, что и переменная $а.

Storing cmdlet output in an array

If the cmdlet generates a stream of objects, they can be stored in an array. Example:

PS С:\Users\andrv> $а = Get-Childltem

The $a variable now contains an array of objects corresponding to the files and subdirectories in the C:\Users\andrv directory. You can work with this array in the usual way:

Теперь в переменной $а содержится массив объектов, соответствующих файлам и
подкаталогам в каталоге C:\Users\andrv. С этим массивом можно работать обычным
способом:
PS С:\Users\andrv> $а.Count
30
PS С:\Users\andrv> $а[О..З]
Каталог: C:\Users\andrv
Mode LastWriteTime Length Name
d---- 15.02.2021 20:30 .config’ d---- 10.10.2020 22:02 .dbus-keyrings
d---- 11.02.2021 16:12 .local
d---- 03.03.2021 20:10 .quokka

Deleting an array

To delete an array, you can use the Remove-Item cmdlet (alias de1) and delete the variable that contains the desired array from the Variab1e virtual disk:

Наприклад:

PS С:\> $а
1
2
3
4
5
6
PS С:\> del Variables
PS С:\> $а
PS С:\>

Hash tables (associative arrays)

In addition to ordinary arrays, PowerShell supports so-called associative arrays (sometimes they are also called dictionaries), which are structures for storing a set of keys and their values, linked in pairs. For example, you can use a person’s last name as a key and their date of birth as a value. An associative array provides a structure for storing a collection of names and dates of birth, with each name associated with a date of birth. Visually, an array of related values can be represented as a table consisting of two columns, where the first column is the key, and the second is the value.

Associative arrays are similar to regular arrays in PowerShell, but instead of accessing the contents of the array by index, you can access the data element of an associative array using keys. Using this key, PowerShell returns the corresponding value from an associative array.

PowerShell uses a special data type, a hash table, to store the contents of an associative array because this data structure provides a fast lookup mechanism. This is very important, since the main purpose of an associative array is to provide an effective search mechanism.

Unlike a normal array, special literals are used to declare and initialize hash tables: $array_name = @{key1 = element!.; <key2 = element2; . . . }

So, each value of the hash table must be assigned a label (key), symbols should be placed before enumerating the contents of the array, and the enumeration of elements ends with the symbol Keys and values are separated by an equal sign (=), key-value pairs are separated by a semicolon ( ; ).

Let’s create, for example, a hash table in which data about one person will be stored (associative array with three elements):

PS С:\> $user = @ (Фамилия="Попов" ; Имя="Андреи"; Телефон="55-55-55"}
PS С:\> $user
Name . Value
Фамилия
Имя
Телефон
Попов
Андрей
55-55-55

After creating an array, you need to learn how to access its elements. There are two ways to access hash tables in PowerShell: using property notation or array notation. Processing using property notation is as follows:

PS С:\> $user.Фамилия
Попов
PS С:\> $изег.Имя
Андрей

With this approach, the hash table is considered as an object: we set the name of the desired property and get the corresponding value. Accessing an associative array using array notation looks like this:

PS С:\> $user["Фамилия”]
Попов
PS С:\> $user["Фамилия", "Имя"]
Попов
Андрей

As you can see, when working with a hash table as an array, you can get values for several keys at once.

Базовым типом для ассоциативных массивов PowerShell является тип
System.Collections.Hashtable:
PS С:\> $user.GetType().FullName
System.Collections.Hashtable

This type defines several properties and methods that can be used (recall that the full list of properties and methods can be obtained using the Get-Member cmdlet). For example, the Keys and Va1ues properties store all keys and all values, respectively:

PS С:\> $user.Keys
Фамилия
Имя
Телефон
PS С:\> $user.Values
Попов
Андрей
55-55-55

Operations with hash tables

Let’s learn how to add, modify and delete elements in a hash table. Let’s add data about a person’s age and the city where he lives to the $user hash table:

PS С:\> $user.Возраст = 33
PS С:\> $user
Name
Возраст
Фамилия
Имя
Телефон
Value
33
Попов
Андрей
55-55-55
PS С:\> $user["Город”] = "Саранск”
PS С:\> $user
Name
Возраст
Город
Фамилия
Имя
Телефон
Value
33
Саранск
Попов
Андрей
55-55-55

Thus, elements are added to an associative array using a simple assignment operator using properties or notations of the array. Let’s change the value of the key that is already in the array. This is also done using the assignment operator:

PS С:\> $user.Город = "Москва"
PS С:\> $user
Name Value
Возраст
Город
Фамилия
Имя
Телефон
33
Москва
Попов
Андрей
55-55-55
Для удаления элемента из ассоциативного массива используется метод Remove ():
PS С:\> $user.Remove("Возраст")
PS С:\> $user
Name
Город
Фамилия
Имя
Телефон
Value
Москва
Попов
Андрей
55-55-55
Можно создать пустую хэш-таблицу, не указывая ни одной пары ’’ключ — значение”. и затем заполнять ее последовательно по одному элементу:
PS С:\> $а = @{}
PS С:\> $а
PS С:\> $a.one = 1
PS С:\> $a.two = 2
PS С:\> $а
Name Value
two
one
2
1

As with regular arrays, the assignment operator operates on a hash table by reference. For example, after executing the following commands, the variables $a and $b will point to the same object:

PS С:\> $а = @{one=l;two=2}
PS С:\> $Ь = $а
PS С:\> $Ь
Name Value
two
one
2
1
Поменяв значение одного из элементов в $а, мы получим тот же результат в $ь:
PS С:\> $а.опе=3
PS С:\> $Ь
Name Value
two
one
2
3

Results

  • Variables and literals in PowerShell are .NET objects.

  • PowerShell supports several kinds of character strings. Decomposition of expressions and variables is performed for strings enclosed in double quotes.

  • PowerShell is a backslash-apostrophe, not a backslash like most other programming languages.

  • Some standard variables are created and modified by PowerShell itself.

  • Custom PowerShell variables are automatically created the first time you assign them values. The type of a variable is determined by the type of its value.

  • When you create and initialize variables in PowerShell, you can specify the type and additional attributes that limit the set of variables that can be used.

  • PowerShell automatically converts types when evaluating expression values. You can perform an explicit conversion by specifying the desired type in square brackets.

  • PowerShell supports arrays and hash tables (associative arrays). Unlike many programming languages, PowerShell does not use any additional characters to indicate the beginning or end of an array. Values added to the array are separated by commas.

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.