PowerShell is a powerful shell and scripting language used to automate tasks, manage the operating system, and interact with various services in a Windows environment. If you’re just starting out in the world of PowerShell, this comprehensive guide will give you everything you need to get off to a flying start. Learning the basics is a key step in mastering PowerShell. You should familiarize yourself with the command structure, variables, functions, and object streams. Studying commandlets (cmdlets) – the basic building blocks of PowerShell, will help you understand how to effectively work with the system. Using PowerShell helps make routine tasks much easier and faster.
You can create scripts that perform repetitive actions and focus on more complex tasks. Learn how to create and execute scripts that will help you optimize your system and increase productivity. In addition, you will learn about the shell interface, working with pipelines, filters and scripts. Understanding these concepts will allow you to more easily perform complex operations and gather information from various sources. The possibilities are endless in the world of PowerShell, so learning the basics is just the first step. This guide will help you gain solid foundational knowledge and skills that will allow you to work more effectively with this powerful command shell. With PowerShell, you can turn your routine tasks into automated processes and make your Windows operating system more productive.
To start a new session in the PowerShell shell, you can select Windows PowerShell from the Start menu. Another way to start the shell is to click the Run button in the Start menu, enter the file name powershe11 and click OK.
As a result, a new window of the standard Windows console will open with an offer to enter commands (Figure 3.1).
If you prefer to work in Windows Terminal (recall that it must first be installed on the system), then a PowerShell session with a prompt to enter a command will open by default after starting the terminal (Figure 3.2).
Take a look at the offer to try the new cross-platform PowerShell. At the time of writing (2021), Windows 10 defaults to Windows PowerShell version 5.1, which is based on the Windows-specific .NET Framework version 4.x. Subsequent versions of PowerShell (sixth and seventh) use .NET Core/.NET 5, which can be installed on Windows, macOS, and Linux. Thus, PowerShell 6/7 is a new shell (started with pwsh, not powershe11) that can run on different operating systems, but needs to be installed separately.
Let’s run the first command in PowerShell and display the contents of the current directory. In the cmd shell, the dir.exe command is used for this, in the bash shell – command 15. Let’s try to run the same commands in PowerShell (note that PowerShell processes commands in case insensitive):
PS С:\Users\andrv> dir Каталог: 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 d---- 11.10.2020 7:48 . ssh d---- 28.09.2020 23:28 .vscode PS С:\Users\andrv> Is d---- 03.03.2021 20:04 .wallaby d-r— 28.09.2020 16:18 3D Objects d-r-- 28.09.2020 16:18 Contacts d----- 01.04.2021 19:41 Documents d-r— 14.05.2021 20:58 Downloads d-r— 28.09.2020 16:18 Favorites d-r— 28.09.2020 16:18 Links d-r— 28.09,2020 16:18 Music dar—1 14.05.2021 20:45 OneDrive d-r-- 28.09.2020 16:18 Saved Games d-r— 28.09.2020 16:18 Searches d-r-- 04.10.2020 23:52 Videos -a--- 18.10.2020 17:20 93 .gitconfig Каталог: 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 d---- 11.10.2020 7:48 . ssh d---- 28.09.2020 23:28 .vscode d---- 03.03.2021 20:04 .wallaby d-r— 28.09.2020 16:18 3D Objects d-r-- 28.09.2020 16:18 Contacts d---- 01.04.2021 19:41 Documents d-r— 14.05.2021 20:58 Downloads d-r— 28.09.2020 16:18 Favorites d-r— 28.09.2020 16:18 Links d-r— 28.09.2020 16:18 Music dar—1 14.05.2021 20:45 OneDrive d-r— 28.09.2020 16:18 Saved Games d-r— 28.09.2020 16:18 Searches d-r— 04.10.2020 23:52 Videos -a--- 18.10.2020 17:20 93 .gitconfig
As you can see, both commands work in the same way, displaying a list of files and subdirectories in the current (home) directory, as well as additional information about them. Shells cmd.exe and bash support output redirection using the symbol > (sign “more”), the result of executing commands can be displayed not as a screen, but as a text file.
Let’s try to do the same in PowerShell:
PS С:\Users\andrv> dir > dir.txt
This command executed without any message on the screen. Let’s now display the contents of the dir.txt file on the screen using the type command
PS С:\Users\andrv> type c:\dir.txt Каталог: С:\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 d---- 11.10.2020 7:48 . ssh d---- 28.09.2020 23:28 .vscode d---- 03.03.2021 20:04 .wallaby d-r— 28.09.2020 16:18 3D Objects d-r— 28.09.2020 16:18 Contacts d---- 01.04.2021 19:41 Documents d-r— 14.05.2021 20:58 Downloads d-r— 28.09.2020 16:18 Favorites d-r— 28.09.2020 16:18 Links d-r— 28.09.2020 16:18 Music dar—1 14.05.2021 20:45 OneDrive d-r-- 28.09.2020 16:18 Saved Games d-r— 28.09.2020 16:18 Searches d-r— 04.10.2020 23:52 Videos -a--- 18.10.2020 17:20 93 .gitconfig
So, here we are: we ran a few familiar commands in the new shell and made sure that PowerShell supports redirection of OUTPUT to a text file.
In addition to executing commands in PowerShell, you can evaluate expressions, such as using the shell as a calculator. Example:
PS С: \Users\andrv> 24-3 5 PS С:\Users\andrv> 10-2*3 4 PS С:\Users\andrv> (10-2)*3 24
As you can see, the result of calculations is immediately displayed on the screen, there is no need to use any special commands for this (it is worth remembering this feature of PowerShell for the future).
The preceding examples show that PowerShell handles the evaluation of integer expressions, including parentheses. Let’s check the expression, the result of which is a floating-point number:
PS С:\Users\andrv> 10/3 3.33333333333333
Here, too, everything is in order, the result is calculated correctly. In fact, you can perform more complex calculations in PowerShell using various math functions. To do this, use the function. NET-k.nacca System.Math. For example, the following command calculates and displays the square root of l69:
PS С:\Users\andrv> [System.Math]::Sqrt(169) 13
In PowerShell, you can store the result of evaluating an expression in a variable and use that variable in other expressions. Example:
PS С:\Users\andrv> $а = 10/2 PS С:\Users\andrv> $а 5 PS С:\Users\andrv> $а * 3 15
Usually, in shells, all commands were divided into internal commands, which are recognized and executed directly by the corresponding interpreter, and external commands, which are separate executable modules. In cmd.exe, for example, internal commands include drr and soru, while external commands include hsor and more. In addition, shells support scripts in the language, which allow you to execute commands in batch mode.
PowerShell supports four types of commands: cmdlets, functions, scripts, and external executables.
The first type of PowerShell commands are called cmdlets, which are internal PowerShell commands. Why is such a strange word used for the name of internal commands? This is because cmdlets aren’t fully built into PowerShell like cmd.exe’s internal commands, but they also can’t be run outside of the shell like regular executables. Therefore, a new term was proposed for their name.
A cmdlet is a .NET class that derives from the Cmd1et base class. A single base class, Cmd1et, ensures syntax compatibility across all cmdlets and automates parsing of command-line parameters and description of cmdlet syntax for built-in help.
This type of command is compiled into a dynamic link library (DLL) and loaded into the PowerShell process when the shell is started (that is, the cmdlets themselves cannot be run as applications, but contain executable objects). Because the compiled code is loaded into the shell process when PowerShell is started, this type of command executes most efficiently.
Cmdlets can be seen in some way as the analogue of internal commands of traditional shells, although, unlike internal commands, new cmdlets can be added to the system at any time. This makes PowerShell an extensible shell and enables Microsoft and other software vendors to add cmdlets to PowerShell to manage their applications and services (such as Microsoft SQL Server or Microsoft Exchange).
Cmdlets can be very simple or very complex, but each is designed to solve one narrow task. Working with cmdlets becomes really efficient when you use composition, when objects are passed from one cmdlet to another (see Chapter 5 for more information on how to pass objects).
Cmdlet names always follow a verb-noun pattern, where the verb indicates a specific action, and the singular noun defines the object on which the action will be performed (“action object”). This convention makes cmdlets much easier to remember and use. For example, use the Get-Process cmdlet to get information about a process, the Stop-Service cmdlet to stop a running service, the C1ear-Host cmdlet to clear the console screen, and so on.
A hyphen is part of a cmdlet name, which, for example, Get-Process is not a combination of Get and Process—the name consists entirely of the words Get—Process.
Cmdlet names are not case sensitive. It is customary to capitalize both words in the name to improve readability of the code, but this is not necessary.
You can use autocompletion when entering cmdlet names at the PowerShell command line. If you type the first few characters and press the <Ta> key, the system will alternately substitute the full names of all corresponding cmdlets.
Cmdlets can have parameters, which are elements that provide additional information. Parameters either specify the elements that the command should work with, or specify how the cmdlet will work. You can refer to parameters by name preceded by a hyphen (-), or by position (in the latter case, the interpretation of the parameter will be performed depending on its location in the command line).
Three types of cmdlet parameters are supported, in general the syntax is as follows:
cmdlet name —parameter1 -parameter2 argument 1 argument2
Here –parameter1 is a parameter that has no value (such parameters are often called parameters),• –parameter2 is the name of a parameter that has an argument value]•, argument2 is a parameter that has no name (or argument). Parameter names, like cmdlet names, are case-insensitive and can be automatically entered as you type by pressing the <Tab> key. As an example of a switch, consider the -Recurse parameter of the GetChi1dItem cmdlet.
The -Recurse switch, if specified, propagates the command not only to a specific directory, but also to all its subdirectories. For example, the following cmdlet will display information about all files that are located in the C:\Program Files\lnternet Explorer directory or one of its subdirectories and have a name that satisfies the mask ie* (as you can see, no argument is specified after the -Recurse option):
PS С:\Users\andrv> dir -Recurse -Filter ie* 'C:\Program Files\ Internet Explorer\' Directory: C:\Program FilesMntemet Explorer Mode LastWriteTime Length Name -a--- 12/7/2019 12:09 PM 515072 iediagcmd.exe -a--- 12/7/2019 12:09 PM 504832 ieinstal.exe -a--- 12/7/2019 12:09 PM 224768 ielowutil.exe -a--- 12/7/2019 12:09 PM 421888 IEShims.dll -a--- 12/7/2019 12:47 AM 819136 iexplore.exe Directory: C:\Program FilesMntemet Explorer\en-US Mode LastWriteTime Length Name -a--- -a--- 1/12/2021 11:02 AM 1/12/2021 11:03 AM 2560 ieinstal.exe.mui 5632 iexplore.exe.mui Directory: C:\Program FilesMntemet Explorer\ru-RU Mode LastWriteTime -a--- 12/7/2019 5:34 PM -a--- 12/7/2019 5:34 PM Length Name 2560 ieinstal.exe.mui 6144 iexplore.exe.mui
This example uses one more parameter — Filter with the ie * argument, which specifies the file mask to search for. Note that the names of the parameters do not have to be specified in full, but the abbreviated name must clearly identify the corresponding parameter.
For example, instead of the last cmdlet, you can execute the following abbreviated version, the result will remain the same: PS C:\Users\andrv> dir -г -fi ie* ‘C:\Program Files\Internet Explorer\’ However, if you try to shorten the name of the -Filter parameter to one character, an error will occur: PS C:\Users\andrv> Get-Childltem : He is unable to process the parameter, because the name of the f parameter is ambiguous. Possible matches: -Filter -Force.
In our example, there is one more argument that specifies the path to the C:\Program FilesMntemet Exlplorer directory. As you can see, no parameter is specified for this argument. In fact, the above command is equivalent to the following: PS C:\Users\andrv>dir -r -f ie* -path •C:\Program Files\lntemet Explorer\’ 50 Part I.
Let’s get acquainted with PowerShell. That is, in this case, the parameter ‘C:\Program Files\Internet ExplorerV’ corresponds to the parameter. The name of the -Path parameter can be omitted – the system will be able to determine that the argument specifying the path to the file system directory refers to this parameter.
Recall that all cmdlets are descendants of the Tnd1et base class, which defines several parameters that provide a consistent, uniform PowerShell interface.
In particular, some options, called global options, are supported by all PowerShell cmdlets (and may not be affected by certain cmdlets). The main general parameters are given in table. 3.1.
Let’s say a few words about the -WhatIf option from the table. 3.1. This parameter allows you to see the objects that will be affected by this or that cmdlet without performing the actions themselves. For example, the following command allows you to see which files in the C:\Tetra directory will be deleted when the de1 command is run (the files themselves are not deleted):
PS С:\> del -Whatlf "С:\temp\*. "С:\temp\xv2p.dll". Whatlf: Выполнение операции "Удаление файла" над целевым объектом "С:\temp\bidiSNMP.dll". Whatlf: Выполнение операции "С:\temp\BiDiSNMP.ini". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "С:\temp\Setup.exe". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "C:\temp\XBASE.DLL". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "С:\temp\XeroxLpr.dll". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "С:\temp\XeroxPM.hlp". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "С:\temp\XPmPrint.ini". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "С:\temp\xrxipdis.dll". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "С:\temp\XSNMX.DLL". "Удаление файла" над целевым объектом Whatlf: Выполнение операции "Удаление файла" над целевым объектом
The -WhatIf parameter can be particularly useful in cases where the range of objects to be affected by the cmdlet is implicitly defined (for example, using regular expressions).
To see a list of cmdlets available during the current session, run the Get-Corrnand command. If you run Get-Corrnand with no parameters, you will see all available commands, including functions and command aliases. You can filter this list to include only cmdlets using the following command pipeline (see Chapter 5 for more information about pipelines):
PS С:\Users\andrv> Get-Command | Where-Object CcmmandType -eq 'Cradlet' | Format-Wide -Column 2 Add-AppvC1i entConnecti onGroup Add-AppvPublishingServer Add-AppxProvisionedPackage Add-Computer Add-History Add-KdsRootKey Add-Member Add-Signe rRu1e Add-AppvClientPackage Add-AppxPackage Add-AppxVolume Add-Content Add-JobTrigger Add-LocalGroupMember Add-PSSnapin Add-Type
The Get-C01Mnand command has -Verb and -Noun options to display cmdlets with a specific verb or noun, respectively. For example, you can see which PowerShell commands can be used to manage processes running on the system:
PS С:\Users\andrv> Get-Command -Noun Process| Format-Wide -Column 2 Debug-Process Start-Process Wait-Process Get-Process Stop-Process Следующая команда покажет, какие объекты можно получить с помощью команд с глаголом Get: PS С:\Users\andrv> Get-Command -Verb Get | Format-Wide -Column 2 Get-AdlAnalyticsAccount Get-AdlAnalуticsDataSource Get-AdlCatalogltem Get-AdlJobPipeline Get-AdlStore Get-AdlStoreFirewallRule Get-AdlAnalyticsComputePolicy Get-AdlAnalyticsFirewallRule Get-AdlJob Get-AdlJobRecurrence Get-AdlStoreChildltem Get-AdlStoreltem
The third type of commands supported by PowerShell are scripts. A script is a block of PowerShell code stored in an external file with the .psl extension. The script’s syntax is analyzed each time it is run.
Scripts allow you to work with PowerShell in batch mode, that is, create a file with the necessary commands in advance, define the logic of work using various control instructions of the PowerShell language, and use this file as an executable module.
See Chapter 9 for more information about PowerShell scripts.
The last type of command you run in PowerShell are external executables, which are executed by the operating system in the normal way. In particular, you can run any external command-line utilities (such as xsoru) from Windows PowerShell by simply specifying their names.
If you want to run a file whose name contains spaces (or a path), enclose the name in single or double quotes and prefix the name with the ampersand & (in PowerShell, this symbol represents the call operator). For example, the following command will launch lnternet Explorer: PS C: \> ” C: \Program Fi1es\Internet exp10rer\iexp10re.exe ‘
As mentioned earlier, the names of all cmdlets in PowerShell follow the “action object” pattern and can be quite long, which makes it difficult to type them quickly. The alias mechanism implemented in PowerShell allows users to run commands under alternate names. PowerShell has many predefined aliases, and you can add your own aliases to the system.
For example, we used the dir command several times, which is actually an alias for the Get-Chi1dItem cmdlet. This can be verified using the Get-C0Inand OR Get-A1ias cmdlet:
PS С:\Users\andrv> Get-Command dir CommandType Name Alias dir -> Get-Childltem PS C:\Users\andrv> Get-Alias dir CommandType Name Alias dir -> Get-Childltem
There are two types of aliases in PowerShell. The first is designed for compatibility of names with different interfaces. These aliases allow users familiar with other shells (cmd.exe or bash) to use familiar command names to perform similar operations in PowerShell. Ego makes it easy to learn a new shell, so you don’t have to spend effort remembering new specific PowerShell commands.
For example, the user wants to clear the screen. If he has experience with cmd.exe, he will naturally try to execute the c1s command. When you do this, PowerShell will automatically run the C1ear-Host cmdlet, for which c1s is an alias, and which performs the required screen cleanup action.
For cmd.exe users, PowerShell defines the aliases cd, c1s, soru, de1, dir, echo, erase, move, popd, pushd, ren, rmdir, sort, type; FOR users of UNIX-like systems – aliases cat, chdir, c1ear, diff, h, history, ki11, 1p, 1s, mount, ps, pwd, r, rm, sleep, tee, write.
The second type of aliases (standard aliases) in PowerShell is for quick command entry. These aliases are derived from the names of the cmdlets they correspond to. For example, the verb Get is shortened to d, set verbs are shortened to s, the noun Location is shortened to 1, and so on. So the Set-Location cmdlet has an alias of 51 and the GetLocation cmdlet has an alias of d1.
You can view a list of all aliases declared in the system using the Get-A1ias cmdlet without parameters:
PS С:\Users\andrv> Get-Alias CommandType Name Alias % -> ForEach-Object Alias ? -> Where-Object Alias ac -> Add-Content Alias asnp -> Add-PSSnapin Alias cat -> Get-Content Alias cd -> Set-Location Alias chdir -> Set-Location Alias clc -> Clear-Content Ali as clear -> Clear-Host Alias clhy -> Clear-History Alias cli -> Clear-Item Alias clp -> Clear-ItemProperty Alias cis -> Clear-Host Alias civ -> Clear-Variable Alias cnsn -> Connect-PSSession Alias compare -> Compare-Object Alias copy -> Copy-Itern Alias cp -> Copy-Itern Alias cpi -> Copy-Item Alias cpp -> Copy-ItemProperty Alias curl -> Invoke-WebRequest Alias cvpa -> Convert-Path Alias dbp -> Disable-PSBreakpoint Alias del -> Remove-Item Alias diff -> Compare-Object
You can set your own alias using the Set-Alias or New Alias cmdlet. For example, let’s create a list alias for the Get-chiiditem cmdlet: PS C:\Users\andrv> Set-Alias -name list -value Get-Childltem
Let’s check how this alias works:
PS С:\Users\andrv> list Каталог: С:\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 d---- 11.10.2020 7:48 . ssh d---- 28.09.2020 23:28 .vscode d---- 03.03.2021 20:04 .wallaby d-r— 28.09.2020 16:18 3D Objects d-r— 28.09.2020 16:18 Contacts d---- 01.04.2021 19:41 Documents d-r— 14.05.2021 20:58 Downloads d-r— 28.09.2020 16:18 Favorites d-r— 28.09.2020 16:18 Links d-r— 28.09.2020 16:18 Music dar—1 14.05.2021 20:45 OneDrive d-r— 28.09.2020 16:18 Saved Games d-r— 28.09.2020 16:18 d-r— 04.10.2020 23:52 -a--- 18.10.2020 17:20 Searches Videos 93 .gitconfig
Multiple aliases can match the same command (for example, GetChi1dItem matches the aliases dir and 1s), but one alias cannot refer to two commands. Created aliases can be reassigned, for example:
PS С:\Users\andrv> Set-Alias list Get-Location PS C:\Users\andrv> list Path C:\Users\andrv
In this example, we assigned the Get-Location cmdlet the alias 1ist, which was previously bound to the Get-Chi1dItem cmdlet. The last example also shows that the names of the -Name and -Va1ue parameters in the Set-A1ias cmdlet can be omitted, but in this case the order in which the alias names (the first parameter) and the corresponding cmdlet (the second parameter) are specified should be followed.
In addition to cmdlets, the PowerShell shell allows you to create aliases for functions, scripts, or executables. For example, the command Set-A1ias pr c: exe will create an alias pr that corresponds to the executable file notepad.exe (Windows Notepad).
In PowerShell, you cannot create an alias for a command with parameters and values.
For example, you can create an alias for the Set-Location cmdlet, but you cannot create an alias for the Set-Location command using: To assign an alias to such a command, you can create a function that contains the command and define an alias for the function. Example:
PS С:\Users\andrv> function CD32 (Set-Location C:\Windows\System32} PS C:\Users\andrv> Set-Alias go cd32 PS C:\Users\andrv> go PS C:\windows\system32> Удалить псевдоним можно с помощью командлета Remove-item, например: PS С:\windows.I\system32> Remove-Item alias:go PS C:\windows.I\system32> go Условие "go” не распознано как командпет, функция, выполняемая программа или файл сценария. Проверьте условие и повторите попытку. строка:1 знак:2 + до <<<<
Aliases can be exported to a text file (Export-A1ias) and imported from a file (Import-A1ias). Thanks to aliases, the syntax of PowerShell becomes flexible: the same commands can be written both very briefly and in an expanded form. This is very important for a language that is both a command-line shell and a scripting language.
When working interactively, it is more convenient to use short aliases and not to fully specify the parameter names to speed up command entry. If you write scripts, it is better to use the full names of cmdlets and their parameters, this will greatly simplify the analysis of the program code later.
All of us have long been accustomed to the structure of the file system as a set of nested folders (directories) and files. In the Windows operating system, the interface to such a structure is provided by the Windows Explorer, the cmd.exe shell, as well as various third-party file managers. In systems, the concepts of files and directories are interpreted more broadly, and various system components (for example, hardware devices or network connections) can act as files here. This approach makes it easier to find the necessary elements in the operating system. Command-line shells or other utilities that access files on [L41X] systems can also work with these components.
PowerShell is similar in this respect in that it allows you to browse and navigate through different data stores using the same familiar routines you use to navigate your file system.
In addition to regular local or network file system drives (C:, D:, and so on), the shell supports special (virtual) PowerShell drives associated with various types of data stores. For example, the root registry key LOCACL MACHINE JEU corresponds to the NKT4: drive, the aliases available in the current session correspond to the Alias: drive, and the digital signature certificate store corresponds to the Cert: drive.
To get a list of PowerShell drives available in the current session, you need to use the Get-PSDrive cmdlet:
PS С:\Users\andrv> Get-PSDrive Name Used (GB) Free (GB) Provider Root Alias Alias C 246.59 121.33 FileSystem C:\ Cert Certificate \ E FileSystem E:\ Env Environment Function Function 58 Часть I. Знакомимся с PowerShell HKCU Registry HKEY_CURRENT_USER HKLM Registry HKEY_LOCAL_MACHINE Variable Variable WSMan WSMan
As you can see, the Get-PSDrive cmdlet for each drive reports the vendor name (vendor column) that supports that drive.
A PowerShell provider is an adapter that allows PowerShell users to access data from a specific specialized storage in a consistent format similar to that of regular file system disks. In this way, PowerShell providers provide access to data that is otherwise difficult to access via the command line.
By default, PowerShell includes several built-in provisions that can be used to access various data stores (Table 3.2).
In addition to the built-in providers, you can create your own PowerShell providers and install providers created by other developers. The list of providers registered with PowerShell can be viewed using the Get-PSProvider cmdlet:
PS С:\> Get-PSProvider Name Capabilities Drives Registry Alias Environment FileSystem Function ShouldProcess, Transactions {HKLM, HKCU} ShouldProcess {Alias} ShouldProcess {Env} Filter, ShouldProcess, С... {С, E} ShouldProcess {Function} Variable Certificate ShouldProcess ShouldProcess WSMan Credentials {Variable} {Cert} {WSMan}
In the Capabi1ities field, the capabilities it possesses are indicated for each provider.
About Shou1dProcess. The provider supports generic options -WhatIf and -Firm, which can be used to test a specific action before executing it directly.
About Fi1ter. The provider supports the -Fi1ter global option for cmdlets that work with the provider’s content.
About credentials. The provider allows you to use other accounts when connecting to data stores.
About transactions. The provider registers transactions that allow you to perform several operations to change data, and depending on the result, confirm all operations or roll them back.
The primary goal of providers is to provide access to disparate data in a familiar, consistent manner. The representation model used in this case is based on file system disks.
The data offered by the provider can be viewed and changed as if they were stored in the form of directories and files on the hard disk. Navigating and viewing the contents of different PowerShell drives is done using the same basic cmdlets.
When working with the file system, we use the concept of the current or working directory. You can refer to files in the working directory by name without specifying the full path to them.
Recall that in the cmd.exe shell, the CD command is used to determine or change the working directory (the full name CHDIR can also be used):
С: \Users\andrv> cd /? Вывод имени либо смена текущего каталога. CHDIR [/D] [диск:][путь] CHDIR [..] CD [/D] [диск:][путь] CD [..] обозначает переход в родительский каталог. Команда CD диск: отображает имя текущего каталога указанного диска. Команда CD без параметров отображает имена текущих диска и каталога.
In the PowerShell shell, the concept of the working (current) directory extends to PowerShell drives as well. You can find out the path to the current directory using the Get-Location command (the pwd alias of this cmdlet corresponds to the bash shell command with similar functionality):
PS С:\Users\andrv> Get-Location Path С:\Users\andrv
To change the current directory (including switching to a different PowerShell drive), use the Set-Location command (aliases cd, chdir, s1). Example:
PS С:\Users\andrv> Set-Location c:\ PS C:\> Set-Location HKLM:\Software PS HKLM:\Software
As you can see, when you enter the Set-Location cmdlet, you clearly don’t get any feedback about its execution. Optionally, you can use the PassThru option, which displays the path to the current directory after running the Set-Location command:
PS HKLM:\Software> Set-Location 'C:\Program Files' -PassThru Path C:\Program Files
In the cmd.exe shell and shells, in addition to the absolute setting of paths to files and folders, relative paths (relative to the working directory) are supported. In this case, the path corresponds to the current directory. (dot), the parent directory of the current directory is the path .. (colon), and the root directory of the current drive is the path \ (backslash). PowerShell preserves this notation. For example (instead of the Set-Location cmdlet, we use its cd alias):
PS C:\Program Files> cd \ -PassThru Path C:\ PS C:\> cd HKIM: \Software -PassThru Path HKLM:\Software PS HKLM:\Software> cd .. -PassThru Path HKLM:\
You can use the Get-chiiditem cmdlet (aliases dir and is) to view items and containers located on a specific PowerShell drive. Naturally, the displayed information will depend on the type of PowerShell disk. For example, let’s execute the Get-childitem cmdlet on the disk that corresponds to the root key of the HKEYCURRENTUSER registry, and on a regular disk of the file system:
PS С:\Users\andrv> cd hkcu: PS HKCU:\> dir Hive: HKEY_CURRENT_USER Name Property AppEvents Console CtrlKeyShortcutsDisabled 0 CursorColor 4294967295 CursorSize 25 DefaultBackground 4294967295 DefaultForeground 4294967295 EnableColorSelection 0 ExtendedEditKey 1 ExtendedEditKeyCustom 0 FilterOnPaste 1 ForceV2 1 FullScreen 0 HistoryBufferSize 50 HistoryNoDup 0 InsertMode 1 LineSelection 1 LineWrap 1 LoadConlme 1 NumberOfHistoryBuffers 4 PopupColors 245 QuickEdit 1 ScreenBufferSize 589889656 PS HKCU:\> cd 'C:\Program Files' PS C:\Program Files> Is Directory: C:\Program Files Mode LastWriteTime Length Name d---- 1/12/2021 11:45 AM AMD d---- 9/10/2019 9:10 AM Android d---- 1/12/2021 10:59 AM ATI Technologies d---- 8/15/2017 2:14 PM Autodesk d---- 2/25/2021 3:40 PM CherryTree 11/20/2018 7:30 AM d----- 1/12/2021 12:01 PM d----- 9/9/2019 3:16 PM da--- 7/7/2017 10:36 AM d----- 12/29/2017 10:33 AM Code Industry Common Files dotnet Far Manager Git
The Get-Chi1dItem cmdlet has several parameters that allow you to view the contents of subdirectories, show hidden items, apply filters to display files by mask, and so on.
In addition to using the standard PowerShell drives, you can use the New-PSDrive cmdlet to create your own drives. To do this, you need to specify three parameters: -Name (the name of the PowerShell drive to be created), -PSProvider (the name of the provider, for example, Fi1eSystem for the file system drive or Registry for the drive corresponding to the registry key) and the path to the root directory of the new drive.
For example, you can create a drive for a specific folder on your hard drive so that you can access it not by the “real” long path, but simply by the drive name. Let’s create a PowerShell drive with the name docs, which will correspond to the folder with documents of a specific user:
PS С:\Users\andrv> New-PSDrive -Name docs -PSProvider FileSystem -Root C: \Users\andrv\Documents Name Used (GB) Free (GB) Provider Root docs 0.00 121.32 FileSystem C:\Users\andrv\Documents Теперь обращаться к новому диску можно точно так же, как и к другим дискам PowerShell: PS С:\Users\andrv> cd docs: -PassThru Path docs:\ PS docs:\> dir Directory: C:\Users\andrv\Documents Mode LastWriteTime Length Name d---- 7/7/2017 10:32 AM FeedbackHub d---- 9/9/2019 3:35 PM IISExpress d---- 9/9/2019 3:35 РМ d---- 9/10/2019 9:32 AM d---- 2/25/2021 4:01 PM d---- 7/7/2017 8:57 AM My Web Sites Visual Studio 2019 Windows Powe rShe11 Записные книжки OneNote
As another example, let’s create a custom CurrVer disk for the LOCAL branch of the NCEU registry, where various important parameters of the operating system are stored:
PS Docs:\> New-PSDrive -Name CurrVer -PSProvider Registry -Root HKLM\Software\Microsoft\Windows\CurrentVersion Name Provider Root CurrentLocation CurrVer Registry HKLM\Software\Microsoft\... Теперь содержимое ветви реестра можно просматривать, не вводя длинного пути, трудного для запоминания: PS docs:\> dir CurrVer:\ Hive: HKLM\Software\MicrosoftWindows\CurrentVersion Name AccountPicture ActionCenter Advert isingInfо Арр Management Арр Paths AppHost Property Enabled : 0 EnableWebContentEvaluation : 1
Common operations, such as file system manipulation, are performed in PowerShell in the same way as in other command-line shells.
In PowerShell, expressions can be evaluated directly on the command line.
About the Shell PowerShell supports four types of commands: cmdlets, functions, scripts, and external executables.
Cmdlets are similar to internal commands in other shells. Compiled cmdlet code is loaded into the PowerShell process when the shell starts, so they run as efficiently as possible. The syntax of all cmdlets is unified, and the names always follow the action-object pattern.
A function in PowerShell is a block of PowerShell code that has a name and remains in memory until the end of the current shell session. When calling a function, you can pass arguments to it by specifying them with a space after the name.
A script is a block of PowerShell code that is stored in an external file with the .ps I extension.
External executables are called from the shell by name (if there are no spaces) or by the call operator
PowerShell supports two types of aliases for commands: standard shortcuts for quick command entry and familiar command names from the cmd and bash shells.
PowerShell providers provide access to virtual disks associated with various types of storage (system registry, digital certificate store, etc.). You can access and work with these virtual disks just as you would file system disks.
Thanks to our team of volunteers for providing information from open sources.