Part 5. Getting to know PowerShell (Working with objects)

25 July 2023 20 minutes Author: Lady Liberty

PowerShell Masterclass: Working with Objects

PowerShell is a powerful shell and scripting language that provides many tools for managing the Windows operating system. One of the key aspects of working with PowerShell is working with objects, which allows you to easily and efficiently manage data and perform a variety of tasks. In the Working with PowerShell Objects tutorial, you’ll learn the basic concepts of working with objects in PowerShell, including creating, reading, modifying, and deleting objects. You’ll also learn how to manipulate data, filter, sort, and group objects to get the results you want. Using real-world examples and hands-on exercises, this guide will help you learn techniques for working with PowerShell objects that will make your work with Windows more efficient and productive.

In the previous sections, we have repeatedly said that all actions in the PowerShell shell are related to operations on objects. It will not be superfluous to remind that an object is a collection of data (fields or properties of an object) and methods of working with this data (methods of an object). The specific structure of an object, that is, the composition of properties and methods, is determined by its type. The type set used in Windows PowerShell is based on the types of the .NET Framework, which is widely used in the Windows operating system. For example, any file on the PowerShell hard drive has a .NET-06RkT of type System. that. Fi1eInfo. An object’s property is information about its attributes. Yes, the System object. that. Fi1eInfo has a Length property that corresponds to the size of the file represented by this object. An object’s method is an action that can be performed on that object. For example, the object System. 10. Fi1eInfo is a soruto method that can be used to copy the file represented by this object at the file system level. The properties and methods of objects are used in PowerShell cmdlets to perform various actions and work with data. As we have already mentioned several times, PowerShell is supported by the command pipeline (composition) mechanism, which simplifies operations on objects.

Pipeline objects in the PowerShell shell

The composition mechanism, where the output stream of one command is redirected to the input stream of another, is perhaps the most valuable concept in command-line interfaces. Pipelines not only reduce the effort associated with entering complex commands, but also make it easier to track the flow of work between teams. A useful feature of pipelines is that they do not depend on the number of items transferred, since the pipeline affects each item separately. As a result, as a rule, the consumption of resources for complex commands is reduced and it becomes possible to receive initial information immediately.

The command pipeline mechanism is very widely used in the Tayuke PowerShell shell, but here the pipeline is not a stream of text, as in all other shells, but objects. At the same time, various manipulations can be performed with pipeline elements: filter objects according to a certain criterion, sort and group objects, change their structure.

A pipeline in PowerShell is a sequence of commands separated by a sign (pipe rod). Each command in the pipeline receives an object from the previous command, performs certain operations on it and passes it to the next command in the pipeline. From the user’s point of view, objects package related information into a form in which the information can be more easily manipulated as a whole and from which certain elements can be extracted when necessary.

It is more convenient to work with data that is transferred between teams in the form of objects than with text information. After all, a team that receives a stream of text from another utility must analyze it, analyze it and select the information it needs, and this can be difficult, since usually the team’s conclusion is more oriented to the visual perception of a person (this is natural for an interactive mode of operation), and not to the convenience of further analysis.

With pipelines of objects, such a problem does not arise, here the necessary information is extracted from the element of the pipeline by simply referring to the corresponding property of the object. However, now a new question arises: how exactly to find out the properties of the objects that are passed through the pipeline? After all, when executing this or that cmdlet, we see only one or several columns of formatted text on the screen. For example, let’s run the Get-Process cmdlet, which displays information about active processes:

PS С:\> Get-Process
Handles NPM(K) РМ (К) WS (К) VM(M) CPU(s) Id ProcessName
158 11 45644 22084 126 159.69 2072 AcroRd32
98 5 1104 284 32 0.10 256 alg
39 1 364 364 17 0.26 1632 ati2evxx
57 3 1028 328 30 0.38 804 atiptaxx
434 6 2548 3680 27 21.96 800 csrss
64 3 812 604 29 0.22 1056 ctfmon
364 11 14120 9544 69 11.82 456 explorer
24 2 1532 2040 29 5.34 2532 Far

In fact, on the screen we see only summarized information (the result of formatting the received data), and not a complete representation of the original object. From this information, it is not clear exactly how many properties the objects generated by the Get-Process command have, and what names these properties have. For example, we want to find all “hanging” processes that are not responding to system requests.

Is it possible to do this with the Get-Process cmdlet, what property should be checked for output objects for this?

To answer such questions, you first need to learn to explore the structure of PowerShell objects, learn what properties and methods these objects have.

Viewing the structure of objects (get-member cmdlet)

To analyze the structure of the objects returned by a particular command, the easiest way to pipe these objects is to use the Get-Member cmdlet (alias dt), for example:

PS С:\> Get-Process | Get-Member
TypeName: System.Diagnostics.Process
Name MemberType Definition
Handles AliasProperty Handles = Handlecount
Name AliasProperty Name = ProcessName
NPM AliasProperty NPM = NonpagedSystemMemorySize
PM AliasProperty PM = PagedMemorySize
VM AliasProperty VM = VirtualMemorySize
WS AliasProperty WS = WorkingSet
Responding Property System.Boolean Responding {get;

As a result, we can see on the screen which objects were returned during the operation of the examined cmdlet (in the example given, it is System. Diagnostics. Process), and a complete list of the object’s elements (in particular, we are interested in the Responding property, which defines “hanging” processes). At the same time, many elements of various types (names of properties and aliases, names of methods, etc.) are displayed on the screen, and such a long list becomes inconvenient to view. The Get-Member cmdlet has a -MemberType parameter that allows you to enumerate only members of an object of a specific type. For example, to display only the elements of an object that are properties of that object, use the -MerrberType parameter with the value Property:

PS С:\> Get-Process I Get-Member -MemberType Property
TypeName: System.Diagnostics.Process
Name
BasePriority
Container
MemberType Definition
Property System.Int32 BasePriority {get;}
Property System.ComponentModel.IContainer...
94
EnableRaisingEvents Property
ExitCode Property
ExitTime Property
Handle Property
HandleCount Property
HasExited Property
Id Property
MachineName Property
Responding Property
System.Boolean EnableRaisingEven...
System.Int32 ExitCode {get;}
System.DateTime ExitTime {get;}
System.IntPtr Handle {get;}
System.Int32 HandleCount {get;}
System.Boolean HasExited {get;}
System.Int32 Id {get;}
System.String MachineName {get;}
System.Boolean Responding {get;}

As you can see, operating system processes correspond to objects that have a lot of properties, but when the Get-Process cmdlet works, only some of them are displayed on the screen. Basically, PowerShell displays objects of various types in several configuration files with the extension .pslxml (.xml), which are located in the directory where the powershell.exe file is installed (the path to this directory is stored in the $PSHome variable). A list of these files can be obtained using the following command:

PS С:\> dir $pshome\*foxmat*.pslxml
Directory: С:\Windows\System32\WindowsPowerShell\vl.О
Mode LastWriteTime Length Name
-a--- 12/7/2019 12:10 PM 12825 Certificate.format.pslxml
-a--- 12/7/2019 12:10 PM 4994 Diagnostics.Format.pslxml
-a--- 12/7/2019 12:10 PM 138013 DotNetTypes.format.pslxml
-a--- 12/7/2019 12:10 PM 10112 Event.Format.pslxml
-a--- 12/7/2019 12:10 PM 25306 FileSystem.format.pslxml
-a--- 12/7/2019 12:10 PM 91655 Help.format.pslxml
-a--- 12/7/2019 12:10 PM 138625 HelpV3.format.pslxml
-a--- 12/7/2019 12:10 PM 206468 PowerShellCore.format.pslxml
-a--- 12/7/2019 12:10 PM 4097 PowerShellTrace.format.pslxml
-a--- 12/7/2019 12:10 PM 8458 Registry.format.pslxml
-a--- 12/7/2019 12:10 PM 16598 WSMan.Format.pslxml

In particular, the formatting rule for the System.Diagnostics.Process type object is in the DotNetTypes.format.pslxml file. It is not recommended to directly edit the configuration files, if necessary, you can create your own formatting files AND WITH THE HELP of the Update-FormatData cmdlet, include them in the files that are automatically loaded. Now that we know what properties the objects that have passed through the pipeline have, we will proceed to consider possible operations on the elements of the pipeline.

Object filtering (de-object)

In PowerShell, you can prune objects in the pipeline, that is, remove objects from the pipeline that do not meet a certain condition. To do this, use the Where-Object cmdlet to inspect each object that passes through the pipeline and pass it further down the pipeline only if the object meets the validation criteria.

The verification itself in Where-Object can be organized in two ways: using a block of code and through comparison operators.

Using a code block

Objects that pass through the pipeline are checked in the block of code that follows the name of the Where-Object cmdlet. A script block is one or more PowerShell commands enclosed in curly braces. The output of the code block in the Where-Object cmdlet must be a logical value: $True (true, in this case the object goes further along the pipeline) or $Fa 1se (false, in this case the object is not transferred further along the pipeline). For example, you can use the following pipeline to display information about stopped services in the system (objects returned by the Get-Service cmdlet with a Status property with a Stop to Stopped property):

PS С:\> Get-Service | Where-Object {$_.Status -eq "Stopped”}
Status Name DisplayName
Stopped Alerter
Stopped AppMgmt
Stopped aspnet_state
Stopped cisvc
Stopped ClipSrv
Оповещатель
Управление приложениями
ASP.NET State Service
Служба индексирования
Сервер папки обмена
Вместо where-object можно использовать его краткие псевдонимы: where или просто символ ?:
PS С:\> Get-Service | where {$_.Status -eq "Stopped”}
PS C:\> Get-Service | ? {$_.Status -eq "Stopped"}
Другой пример: оставим в конвейере только те процессы, у которых значение идентификатора (свойство id) больше 1000:
PS С:\> Get-Process | Where-Object {$_.Id -gt 1000}
Handles NPM (К) РМ(К) WS (К) VM(M) CPU(s) Id ProcessName
158 9 37768 26620 125 28.49 1752 AcroRd32
39 1 364 420 17 0.16 1632 ati2evxx
57 3 1028 804 30 0.40 1988 atiptaxx
24 2 1460 1052 29 0.62 2084 Far
720 75 38516 10508 153 50.96 1756 kavsvc
36 2 728 32 23 0.06 1792 klswd
33 2 792 1984 25 1.15 1412 notepad
242 158 30544 5780 180 7.96 1784 outpost
252 5 34384 27192 137 5.15 2904 powershell
143 5 3252 1028 42 0.31 1528 spoolsv
194 5 2928 1340 59 0.34 1040 svchost
301 14 1784 1316 37 0.80 1116 svchost
1647 65 20820 11548 101 13.21 1152 svchost
55 3 1088 724 27 0.46 1224 svchost
170 6 1568 960 35 0.14 1604 svchost
120 4 2356 1292 35 0.22 1876 svchost
22 2 504 584 23 0.06 1764 winampa
430 13 8472 11352 246 57.63 3216 WINWORD
154 4 2112 2104 38 28.13 2032 wmiprvse

Where-Object cmdlet code blocks use the special $ variable to access the current pipeline object and retrieve the desired properties of that object, which are automatically generated by PowerShell.

NOTE This variable is also used in other cmdlets that process pipeline elements.

As you can see from the examples, the code block uses special comparison operators. The main comparison operators are given in table. 5.1.

NOTE PowerShell does not use the normal > or < characters for comparison operators because they mean I/O redirection on the command line.

Table 5.1. Comparison operators in the PowerShell shell

Comparison operators can be connected with each other using logical operators (Table 5.2).

 

Using the comparison operator

Starting with version 3, PowerShell supports a simpler and more natural language version of the Where-Obj ect cmdlet.

You don’t need to enclose a block of code in curly braces and use the $ variable to access the object that comes through the pipeline. All you need to do is specify the property to filter by, the comparison operator to use (in this case, the Where-Object cmdlet parameter), and the value the object property is compared to. Example:

PS С:\Users\andrv> Get-Service | Where-Object -Property Status -eq -Value
"Stopped”
98 Часть I. Знакомимся с PowerShell
Status Name DisplayName
Stopped Alerter Оповещатель
Stopped AppMgmt Управление приложениями
Stopped aspnet state ASP.NET State Service
Stopped cisvc Служба индексирования
Stopped ClipSrv Сервер папки обмена
Названия параметров -Property И -Value МОЖНО опустить, а вместо Where-Object
использовать псевдоним where. В этом случае фильтрация будет выглядеть кратко и
выразительно:
PS С:\> Get-Service | where Status -eq "Stopped"
Status Name
Stopped Alerter
Stopped AppMgmt
Stopped aspnet state
Stopped cisvc
Stopped ClipSrv
DisplayName
Оповещатель
Управление приложениями
ASP.NET State Service
Служба индексирования
Сервер папки обмена

Sorting objects (Sort-Object)

Sorting pipeline items is another common operation performed by the Sort-Object cmdlet (alias sort). This cmdlet passes the names of the properties by which to sort the objects passing through the pipeline, and returns the data ordered by the values of those properties.

For example, you can use the following pipeline to get a list of processes running on the system, ordered by CPU time (the sri property):

PS С:\> Get-Process | Sort-Object -Property cpu
Handles NPM(K) PM(K) WS (K) VM(M) CPU(s) Id ProcessName
0 0 0 16 0 0 Idle
36 2 728 32 23 0.05 1792 klswd
98 5 1104 764 32 0.09 252 alg
21 1 164 60 4 0.09 748 smss
39 1 364 464 17 0.12 1644 ati2evxx
163 6 1536 1404 35 0.12 1612 svchost
55 3 1088 852 27 0.14 1220 svchost
22 2 504' '712 23 0.14 772 winampa
120 4 2364 1228 35 0.26 1876 svchost
193 5 2916 1488 59 0.29 1040 svchost
64 3 812 1080 29 0.30 1252 ctfmon
140 5 3208 1220 41 0.32 1524 spoolsv
281 14 1764 1688 37 0.34 1120 svchost
57 3 1028 996 30 0.39 932 atiptaxx
503 52 7296 3596 51 2.47 836 winlogon
259 6 1432 1340 19 2.48 880 services
341 8 3572 185§ 40 5.36 892 lsass
240 158 29536 10388 175 5.58 1780 outpost
149 4 2940 1108 41 9.29 1248 kav
398 5 36140 26408 137 9.97 1984 powershell
375 12 15020 10456 75 14.03 1116 explorer
376 0 0 36 2 14.97 4 System
409 6 2500 3192 26 20.10 812 csrss
1513 54 13528 9800 95 25.78 1156 svchost
717 75 37432 704 145 56.97 1748 kavsvc
152 4 2372 2716 38 58.09 2028 wmiprvse
307 13 10952 27080 173 9128.03 1200 WINWORD
Параметр -Property В КОМаНДЛете Sort-Object используется по умолчанию, поэтому
имя этого параметра можно не указывать. Для сортировки в обратном порядке
используется параметр -Descending:
PS С:\> Get-Process | Sort-Object cpu -Descending
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
307 13 10956 27040 173 9152.23 1200 WINWORD
152 4 2372 2716 38 59.19 2028 wmiprvse
717 75 37432 1220 145 57.15 1748 kavsvc
1524 54 13528 9800 95 26.13 1156 svchost
410 6 2508 3224 26 20.62 812 csrss
376 0 0 36 2 15.11 4 System
377 13 15020 10464 75 14.20 1116 explorer
374 5 36484 26828 137 10.53 1984 powershell
149 4 2940 1108 41 9.34 1248 kav
240 J 58 29536 10388 175 5.61 1780 outpost
344 8 3572 1856 40 5.40 892 lsass ' 512 53 7324 3608 51 2.51 836 winlogon
259 6 1432 1340 19 2.48 880 services
57 3 1028 996 30 0.39 932 atiptaxx
281 14 1764 1688 37 0.34 1120 svchost
140 5 3208 1220 41 0.32 1524 spoolsv
64 3 812 1080 29 0.30 1252 ct fmon
193 5 2916 1488 59 0.29 1040 svchost
120 4 2364 1228 35 0.26 1876 svchost
22 2 504 712 23 0.15 772 winampa
55 3 1088 852 27 0.14 1220 svchost
39 1 364 464 17 0.13 1644 ati2evxx
163 6 1536 1404 35 0.12 1612 svchost
21 1 164 60 4 0.09 748 smss
98 5 1104 764 32 0.09 252 alg
36 2 728 32 23 0.05 1792 klswd
0 0 0 16 0 0 Idle
В рассмотренных нами примерах конвейеры состояли из двух командлетов. Это не
обязательное условие, конвейер может объединять и большее количество команд,
например:
PS C:\> Get-Process | Where-Object Id -gt 1000 | Sort-Object cpu -Descending
Handles NPM(K) РМ (К) WS (К) VM(M) CPU(s) Id ProcessName
307 13 10956 27040 173 9152.23 1200 WINWORD
152 4 2372 2716 38 59.19 2028 wmiprvse
717 75 37432 1220 145 57.15 1748 kavsvc
1524 54 13528 9800 95 26.13 1156 svchost
377 13 15020 10464 75 14.20 1116 explorer
374 5 36484 26828 137 10.53 1984 powershell
149 4 2940 1108 41 9.34 1248 kav
240 158 29536 10388 175 5.61 1780 outpost
281 14 1764 1688 37 0.34 1120 svchost
140 5 3208 1220 41 0.32 1524 spoolsv
64 3 812 1080 29 0.30 1252 ct fmon
193 5 2916 1488 59 0.29 1040 svchost
120 4 2364 1228 35 0.26 1876 svchost
55 3 1088 852 27 0.14 1220 svchost
39 1 364 464 17 0.13 1644 ati2evxx
163 6 1536 1404 35 0.12 1612 svchost
36 2 728 32 23 0.05 1792 klswd
В результате выполнения последнего конвейера из трех командлетов мы получили
упорядоченный по количеству затраченного процессорного времени список процессов, идентификатор которых больше 1000.

Selection of objects and properties (Select-Object)

PowerShell has a cmdlet called Se1ect-Object (alias se1ect) that allows you to select a given number of objects from the start of the command line to the end of the pipeline, select unique objects from the pipeline, and extract specific properties on objects that pass through the pipeline.

To select the first or last object from the pipeline, use the -First or -Last options of the Se1ectObject cmdlet, respectively. For example, the following command pipeline will display information about the five most recent processes using the most memory:

PS C:\> Get-Processt I Sort-Object WS | Select-Object -Last 5
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
398 12 14736 8096 78 12.99 740 explorer
1638 66 21368 12292 103 30.03 1152 svchost
280 12 10252 14900 139 124.56 3216 WINWORD
158 9 37776 19704 125 36.21 1752 AcroRd32
297 6 38408 20844 137 8.53 2904 powershell

Let’s take a look at how this command pipeline works. The first pipeline cmdlet (GetProcess) returns an array of objects that correspond to processes running on the system. The second cmdlet (Sort-Object) sorts pipeline objects by the value of the ws property (the amount of memory used by the process). Finally, the third cmdlet (Se1ect-Object) selects the last five elements from the ordered object array.

Suppose now that we want to get a list of processes running on the system, in which only the process names and their identifiers would be specified.

If we don’t remember the names of the properties we need, we can use the Get-Member cmdlet to view the structure of the objects returned by the Get-Process command:

PS С:\> Get-Process | Get-Member -MamberType Property
TypeName: System.Diagnostics.Process
Name MemberType Definition
BasePriority Property System.Int32 BasePriority {get;
Id Property System.Int32 Id {get;}
ProcessName Property System.Strinc[ ProcessName {get;
WorkingSet64 Property„ System.Int64 WorkingSet64 {get;
Итак, В ИТОГОВЫХ объектах нам нужно оставить ТОЛЬКО свойства ProcessName И Id.
Это можно сделать, указав имена нужных свойств в качестве параметров командлета Select-Object:
PS С:\> Get-Process | Select-Object ProcessName, Id
ProcessName Id
AcroRd32 1752
alg 256
102 Часть I. Знакомимся с PowerShell
ati2evxx 1632
atiptaxx 1988
csrss 804
ctfmon 872
explorer 740
Far 2084
Idle 0
kav 884
kavsvc 1756
klswd 1792
lsass 892
outpost 1784
powersftell 2904
Посмотрим теперь, какой тип имеет объект, формируемый в конвейере командлетом select-object, и какие свойства имеются у этого объекта:
PS С:\> Get-Process | Select-Object ProcessName, Id | Get-Member
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
Equals Method
GetHashCode Method
GetType Method
ToString Method
System.Boolean Equals(Object obj)
System.Int32 GetHashCode()
System.Type GetType()
System.String ToString()
Id NoteProperty System.Int32 Id=1752
ProcessName NoteProperty System.String ProcessName=AcroRd32

As you can see, the output object is of type System. . Automation.

PSCustomObject (recall that the Get-Process cmdlet returned objects of the type System. Diagnostics. Process) and has only two properties – ProcessName AND Id. This is because when you use the Se1ect-Object cmdlet to select specified properties, it copies the values of those properties from the pipeline to it and creates new objects that contain the specified properties with the copied values.

In addition to removing unnecessary properties from objects, the Se1ect-Obj ect cmdlet can also add new computational properties. To do this, the new property must be presented in the form of a hash table, where the first element (Name key) corresponds to the name of the added property, and the second element (Expression key) corresponds to the value of this property for the current element of the pipeline. For example, the result of the following command pipeline will be an array of objects that have the properties ProcessNane (the name of the running process) and StartMin (the minute the process started):

PS С:\> Get-Process | Select-Object ProcessName, @ {Name="StartMin”;
Expression = {$_. StartTime. Minute}}
ProcessName StartMin
alg
ati2evxx
atiptaxx
csrss
ctfmon
explorer
45
45
48
45
48
48

Here the StartMin property is calculated, its value for each element of the pipeline is given by the block of code ( $ . StartTime . Minute}, where the $ variable corresponds to the current pipeline object.

Execution: performing arbitrary actions on objects in the pipeline (ForEach-Object Cmdlet)

The ForEach-Object cmdlet allows you to run a specific block of PowerShell code for each object in the pipeline. In other words, this cmdlet can be used to perform arbitrary operations on pipeline elements.

For example, let’s calculate the total amount of files stored in your home directory, the path to which is stored in the $NAME environment variable. To do this, first go to this directory, declare the variable $Tota 1Length and reset it:

PS С:\> cd с:\
PS С:\Users\andrv> $TotalLength=0
Теперь выполним команду dir (напомним, что это псевдоним командлета
Get-chiiditem) и результат ее работы передадим по конвейеру командлету ForEachObject:
PS С:\Users\andrv> dir | ForEach-Object {$TotalLength+=$_.length}
В блоке кода командлета ForEach-Object к текущему значению переменной
$TotaiLength прибавляется значение свойства Length проходящего через конвейер
объекта (размер соответствующего этому объекту файла). В результате в переменной $TotaiLength будет храниться общий размер файлов в байтах:
PS С:\Users\andrv> $TotalLength
17809
Если из объектов, проходящих по конвейеру, нужно лишь извлечь определенное
свойство, то можно просто указать имя этого свойства в качестве параметра
ForEach-Object:
PS C:\Users\andrv> dir | ForEach-Object name
Псевдонимами ДЛЯ командлета ForEach-Object ЯВЛЯЮТСЯ foreach и символ %:
PS C:\Users\andrv> dir | foreach name
PS C:\Users\andrv> dir | % ($TotalLength+=$_. length}

Grouping of objects (group-object)

Pipeline objects can be grouped by the value of certain properties using the Group-Object cmdlet. Objects that have the same values of the specified properties will fall into one group (the properties can be calculated).

Let’s look at an example. The Get-Process cmdlet generates objects that have the property Sotrapu (the name of the company that is the developer of a specific module that runs as a process in the operating system). Let’s group these objects by the value of the Sotrap property:

PS С:\> Get-Process | Group-Object Company
Count Name Group
1 Adobe Systems Incorpor... {AcroRd32}
13 Microsoft Corporation {alg, ctfmon, lsass, OUTLOOK.
7 {csrss, Idle, kav, kavsvc...)
5 Корпорация Майкрософт {explorer, MAPISP32, scardsvr
1 Eugene Roshal & FAR Group {Far}
2 Intel Corporation {hkcmd, igfxpers}
1 Корпорация Microsoft {jview}
1 Kaspersky Lab {kinagent}
1 Visioneer Inc {OneTouchMon}
1 Hewlett-Packard {sdlaunch}
1 Realtek Semiconductor ... {SOUNDMAN}

As you can see, the Count column shows the number of items in each of the groups, and the Group column lists the items that belong to the groups. If you just need to know the number of elements in groups, you can run the Group-Object cmdlet with the -NoE1ement parameter:

PS С:\> Get-Process | Group-Object Company -NoElement
Count Name
1 Adobe Systems Incorpor...
13 Microsoft Corporation
7
5 Корпорация Майкрософт
1 Eugene Roshal & FAR Group
2 Intel Corporation
1 Корпорация Microsoft
1 Kaspersky Lab
1
1 Visioneer Inc
1 Hewlett-Packard
1 Realtek Semiconductor ...

Measurement object characteristics (Measurement object cmdlet)

Another useful cmdlet in PowerShell is Measure-Obj ect, which is designed to perform aggregation functions (sum, minimum, maximum, or average) of item properties in the object pipeline.

Let’s look at an example. Previously, we already found the total size of the files in our home directory using the ForEach-Obj ect cmdlet:

PS С:\Users\andrv> $TotalLength=0
PS C:\Users\andrv> dir | ForEach-Object ($TotalLength+=$_.length}
PS C:\Users\andrv> $TotalLength
17809

Using the Measure-Object cmdlet, we can also find the total size of the files. To do this, you need to specify that the Measure-Object should summarize (parameter -sun) the value of the Length property for all elements of the pipeline:

PS С: \Users\andrv> dir | Measure-Object -Property Length -Sum
Count
Average
Sum
Maximum
Minimum
Property
5
17809
Length

The result will be displayed in the sum field. To perform other operations, you need to specify the appropriate parameter: -Average to find the average value, -Minirrun, or to find the minimum or maximum value, respectively:

PS С:\> dir | Measure-Object -Property Length -Minimum -Maximum -Average -Sum
Count : 5
Average
Sum
: 6433.63636364
: 17809
Maximum : 12458
Minimum : О
Property : Length

The Measure Object cmdlet can also be used to obtain statistical information about text files, such as the number of lines, words, and characters.

References to static methods and fields

Sometimes, when working with PowerShell, you may want to use methods defined in .NET Framework classes (types) without creating or using instances of those classes. Such classes are called static because they are not created, destroyed, or modified. In particular, the System.Math class is a static class whose methods are often used for mathematical calculations.

To denote a static class, enclose its name in square brackets, for example:

PS С:\> [System.Math]
IsPublic IsSerial Name BaseType
True False Math System.Object
Для класса [System.Math] в PowerShell определена краткая аббревиатура [math].
PS C:\> [math]
IsPublic IsSerial Name BaseType
True False Math System.Object

Methods and properties defined in a static class are also called static methods and fields. To view, you need to pass the name of the desired class (in square brackets) through the pipeline to the Get-Member cmdlet with the -Static parameter:

PS С:\> [math] | Get-Member -Static
TypeName: System.Math
Name MemberType Definition
Abs Method static System.Single Abs(Single va
Acos Method static System.Double Acos(Double d
Asin Method static System.Double Asin(Double d
Atan Method static System.Double Atan(Double d
Atan2 Method static System.Double Atan2(Double
BigMul Method static System.Int64 BigMul(Int32 a
Ceiling Method static System.Double Ceiling(Doubl
Cos Method static System.Double Cos(Double d)
Cosh Method static System.Double Cosh(Double v
DivRem Method static System.Int32 DivRem(Int32 a .
Equals Method static System.Boolean Equals(Objec .
Exp Method static System.Double Exp(Double d)
Floor Method static System.Double Floor(Double .
IEEERemainder Method static System.Double IEEERemainder.
Log Method static System.Double Log(Double d).
Log 10 Method static System.Double LoglO(Double
Max Method static System.SByte Max(SByte vail.
Min Method static System.SByte Min(SByte vail.
Pow Method static System.Double Pow(Double x, .
ReferenceEquals Method static System.Boolean ReferenceEqu.
Round Method static System.Double Round(Double .
Sign Method static System. Int32 Sign(SByte val.
Sin Method static System.Double Sin(Double a)
Sinh Method static System.Double Sinh(Double v
Sqrt Method static System.Double Sqrt(Double d
Tan Method static System.Double Tan(Double a)
Tanh Method static System.Double Tanh(Double v
Truncate Method static System.Decimal Truncate(Dec.
E Property static System.Double E {get;}
PI Property static System.Double PI {get;}

As you can see, the methods and fields of the System.Math class implement various mathematical functions and constants, and they are easy to recognize by their name. To access a specific static method or property, two consecutive colons are used, rather than a period (.) as in regular objects. For example, to calculate the square root of a number (static sqrt method) and store the result in a variable, the following construction is used:

PS С:\> $а=[math]::Sqrt(25)
PS С:\> $а
5

Many .NET Framework classes have static methods and fields, with their help, for example, you can:

  • Work with strings (class [System. String], abbreviation [String]);

  • Store reading AND CALCULATE date AND time (class [System. DateTime] with abbreviation [datetime]);

  • Calculate time intervals or the difference between two time readings (class [System.TimeSpan] Abbreviated [timespan]);

  • Convert values from one numeric format to another (class [System. Convert ])

Results

  • PowerShell, like all shells, uses a command pipeline mechanism. However, in PowerShell, the pipeline is not a stream of text, as in all other shells, but objects with properties and methods.

  • You can find out the structure of pipeline objects using the Get-Member cmdlet.

  • You can perform various manipulations with the elements of the conveyor: filter objects according to a certain criterion, sort and group objects, change their structure.

  • Using object pipelines in PowerShell is an example of a declarative approach to programming. PowerShell pipelines are used where other programming languages use looping and expression evaluations (imperative approach).

  • PowerShell provides access to the properties and methods of .NET static classes. So you can use many of the math functions or functions available in .NET to work with strings and dates.

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.