Part 4. Getting to know PowerShell (Working in the PowerShell shell)

25 July 2023 24 minutes Author: Lady Liberty

A complete guide to working with the PowerShell shell

PowerShell is a powerful tool that allows system administrators, developers, and other professionals to effectively manage the Windows operating system. This command shell is developed by Microsoft and provides a high level of automation and flexibility in performing a variety of tasks. In this part, you will learn the basic concepts and syntax of PowerShell, learn to perform various operations with files, registry, network and active directories. We will present you with examples of using commands and scripts to effectively work with the system. With PowerShell, you can automate routine tasks, quickly configure and optimize your system, and ensure data security and protection.

You will learn how to create your own scripts to automatically perform tasks and interact with other programs. Our guide will help you master PowerShell from a beginner level to advanced techniques, allowing you to become more productive and efficient in your work with the Windows operating system. Discover all the possibilities of PowerShell and implement new solutions to successfully manage your system. When working in the command line, you have to manually enter commands that can be quite long and have many different parameters that are difficult to remember. Therefore, it is important to learn to correctly use the help system available in the system, as well as to use the capabilities of the shell to quickly type commands or call them repeatedly. When working in the command line, you have to manually enter commands that can be quite long and have many different parameters that are difficult to remember. Therefore, it is important to learn to correctly use the help system available in the system, as well as to use the capabilities of the shell to quickly type commands or call them repeatedly.

PowerShell command-line editing

In the PowerShell command line, some editing options are available when text is entered (table 4.1).

If you are working in Windows Terminal, you can use special keyboard shortcuts to control the terminal itself (for example, change the font size and open panels on the screen). These combinations can be viewed on the Actions tab in the terminal settings (Fig. 4.1).

Fig. 4.1. Keyboard shortcuts for controlling the Windows terminal

If necessary, the combination can be changed, for this you need to edit the settings.json configuration file, the link to open it is also on the Actions tab in the terminal settings.

You can use the Windows buffer when using PowerShell. If you use a standard Windows console, you can select and copy text to the clipboard from the PowerShell window as follows: right-click on the title bar of the PowerShell window (or any mouse button on the window icon), select the “Edit and Mark” item in the context menu, then use the cursor keys while holding down the <Shift> key, selecting the desired block of text (you can also select it with the mouse while holding its left button) and press the <Enter> key . You can select the entire contents of the PowerShell window by choosing Edit and Select from the same context menu. To paste text from the Windows clipboard into the PowerShell command window (at the current cursor position), select Edit and Paste.

You can simplify manipulations with the Windows buffer in the standard console by enabling the mouse selection and quick insertion modes. To do this, right-click on the title bar of the PowerShell window, select the Properties item from the context menu, and in the Edit section of the Settings tab of the Windows PowerShell Properties dialog box, check the Minching and Quick Paste flags (Figure 4.2). After that, you can select the text with the mouse by pressing the left button. To copy the selected fragment to the clipboard, it is enough to press the <Enter> key or click with the right mouse button. Text from the clipboard is also pasted at the current cursor position by right-clicking.

Fig. 4.2. Configuring the properties of the standard Windows console

If Allow keyboard shortcuts with CONTROL is selected, you can copy selected text to the clipboard by pressing <Ctrl>+<c> or <Ctrl>+ +<lnsert> and paste text from the clipboard by pressing <Ctrl>+<v> or <Shift>+<Insert>.

Windows Terminal Tayuke supports mouse selection and quick paste modes, you can copy text to the clipboard and paste it from the clipboard using the same combinations <Ctrl>+<c>/<Ctrl>+<Insert> and <Ctrl>+<v>/<Shift>+<lnsert>.

In fact, most of those listed in the table. 4.1 Key combinations are implemented at the terminal level, i.e. they work the same in all Windows console applications. In the PowerShell shell itself, another important editing feature is the auto-completion of commands and their options as you type them.

Autocompletion of commands

While in PowerShell, you can type part of a command, press the <TaB> key, and the system will try to execute the command itself.

Such automatic completion works, firstly, for file names and paths to the file system (this mode is also supported by the cmd.exe shell). When you press the <T> key, PowerShell will automatically expand the partially entered filesystem path to the first match it finds. When the <TaB> key is pressed again, a cyclic transition is performed according to the available selection options. For example, we need to go to the C:\Program Files directory. We enter the cd command in the PowerShell command line and specify the beginning of the name of the directory we need as a parameter:

PS С:\Users\andrv> od c:\pro
Нажмем теперь клавишу <ТаЬ>, и система автоматически дополнит путь к каталогу:
PS С:\Users\andrv> cd 'C:\Program Files'

As you can see, the name of the directory containing spaces is enclosed in apostrophes.

As you can see, the name of the directory containing spaces is an apostrophe. PowerShell also implements the ability to automatically complete file system paths based on pattern characters: ? (replaces one arbitrary character) and * (replaces any number of arbitrary characters). For example, if you enter the command cd c:\pro*fiies in PowerShell and press the <Tab> key, the command cd ‘C:\Program Files’ APPEARS AGAIN in the input line. Chapter 4. Working in the PowerShell shell 69 Second, PowerShell implements automatic completion of cmdlet names and their parameters. If you enter the first part of the cmdlet name (verb) and a hyphen, then press the <Tab> key, the system will substitute the name of the first corresponding cmdlet (the next variant of the name is selected by pressing <Tab> again). For example, enter the verb get- in the PowerShell command line:

PS С:\Users\andrv> getНажмем клавишу <Tab>:
PS С:\Users\andrv> Get-Acl
Еще раз нажмем клавишу <ТаЬ>:
PS С:\Users\andrv> Get-Alias
Нажимая далее клавишу <ТаЬ>, мы можем перебрать все командлеты, начинающиеся с глагола Get.
Аналогичным образом автоматическое завершение срабатывает для частично введенных имен параметров командлета: нажимая клавишу <ТаЬ>, мы будем циклически перебирать подходящие имена. Например, введем в командной строке
PowerShell следующий командлет:
PS С:\Users\andrv> Get-Alias -
Нажмем клавишу <ТаЬ>:
PS С:\Users\andrv> Get-Alias -Name
Как видите, система подставила в нашу команду параметр -Name. Еще раз нажмем
клавишу <ТаЬ>:
PS С:\Users\andrv> Get-Alias -Exclude
Нажимая далее клавишу <ТаЬ>, мы можем перебрать все параметры, поддерживающиеся командлетом Get-Alias.
В-третьих, PowerShell позволяет автоматически завершать имена используемых
переменных. Например, создадим переменную $stringvariabie:
PS С:\Users\andrv> $StringVariable=’asdfg'
Введем теперь часть имени этой переменной:
PS С:\Users\andrv> $str
Нажав клавишу <ТаЬ>, мы получим в командной строке полное имя нашей переменной:
PS С:\Users\andrv> $Stringvariable
Наконец, PowerShell поддерживает автоматическое завершение имен свойств и методов объектов. Например, введем следующие команды:
PS С:\Users\andrv> $s='qwerty'
PS С:\Users\andrv> $s.len
70 Часть I. Знакомимся с PowerShell
Нажмем клавишу <ТаЬ>:
PS С:\Users\andrv> $s.Length
Система автоматически подставила свойство Length, имеющееся у символьных
переменных. Если подставляется имя метода (функции), а не свойства, то после его
имени автоматически ставится круглая скобка. Например, введем следующую
команду:
PS С:\Users\andrv> $s.sub
Нажмем клавишу <ТаЬ>:
PS С:\Users\andrv> $s.Substring(
Теперь можно вводить параметры метода Substring.

Entering a command in several lines

By default, pressing the <Enter> key completes the execution of the command, after which the shell begins to parse and execute the command. If you specify the backslash character ‘ as the last character on a line, the command continues on the next line. In this case, the newline character is treated as a normal space separator.

For example, let’s calculate the value of the expression 10+2-3+ (5*4-3), placing it in three lines:

PS С:\Users\andrv> 10+'
» 2-3+('
» 5*4-3)
26

As you can see, the prompt changes to >> characters when additional lines are entered – this is a sign that the previous command is still being entered.

PowerShell Help

When working with an interactive command shell, it is important to have a detailed and convenient help system at hand, which describes the capabilities of commands and examples of their use. PowerShell has such a system, and there are several ways to get help inside the shell.

PS С:\Users\andrv> Get-Process -?
ИМЯ
Get-Process
СИНТАКСИС
Get-Process [[-Name] <string[]>] [-ComputerName <string[]>] [-Module]
[-FileVersionlnfo] [<CommonParameters>]
Get-Process [[-Name] <string[]>] -IncludeUserName [<CommonParameters>]
Get-Process -Id <int[]> -IncludeUserName [<CommonParameters>]
Get-Process -Id <int[]> [-СотриterName <string[]>] [-Module]
[-FileVersionlnfo] [<CommonParameters>]
Get-Process -Inputobject <Process[]> -IncludeUserName [<CommonParameters>]
Get-Process -Inputobject <Process[]> [-ComputerName <string[]>] [-Module]
[-FileVersionlnfo] [<CommonParameters>]
ПСЕВДОНИМЫ
gps
ps
ЗАМЕЧАНИЯ
Get-Help cannot find the Help files for this cmdlet on this computer.
It is displaying only partial help.
— To download and install Help files for the module that includes this
cmdlet, use Update-Help.
— To view the Help topic for this cmdlet online, type: "Get-Help Get-Process
-Online" or go to https://go.microsoft.com/fwlink/7LinkI0113324.
На самом деле при вводе команды Get-Process -? срабатывает специальный командлет Get-Help, Т. е. обратиться К справке ДЛЯ командлета Get-Process можно так:
PS С:\Users\andrv> Get-Help Get-Process

As you can see, the built-in help lists the valid variants of the cmdlet syntax and its aliases. Optional parameters are displayed in square brackets. If an argument of a certain type must be specified for the parameter, then the name of this type is given in angle brackets after the name of such a parameter.

In early versions of PowerShell, help files were local by default, but now detailed help information is stored online at Microsoft sites. It can be accessed from the command line using the Get-He1p cmdlet with the -0nline option: PS C: \Users\andrv> Get—He1p Get—Process —0n1ine

In this case, a detailed description of the Get-Process cmdlet will open in the browser (see Figure 4.3).

Fig. 4.3. Online information about the PowerShell cmdlet

Help information can also be opened in a separate dialog box instead of in the browser. The -ShowWindow parameter (Figure 4.4) is used for this: PS C: \Users\andrv> Get—He1p Get—Process —ShowWindow The Update-He1p cmdlet can be used to download help files to a computer for faster access. After the help files are installed locally, cmdlet information will be displayed in a more complete format. Example:

Fig. 4.4. Help about the cmdlet in the dialog box
PS С:\Users\andrv> Get-Help Get-Process
NAME
Get-Process
ОПИСАНИЕ
Gets the processes that are running on the local computer or a remote
computer.
СИНТАКСИС
Get-Process [[-Name] <System.String[]>] [-СотриterName <System.String[]>]
[-FileVersionlnfo] [-Module] [<CommonParameters>]
Get-Process [-ComputerName <System.String[]>] [-FileVersionlnfo]
-Id <System.Int32[]> [-Module] [<CommonParameters>]
Get-Process [-ComputerName <System.String[]>] [-FileVersionlnfo]
-Inputobject <System.Diagnostics.Process[]> [-Module] [<CommonParameters>]
Get-Process -Id <System.Int32[]> -IncludeUserName [<CommonParameters>]
Get-Process [[-Name] <System.String[]>] -IncludeUserName
[<CommonParameters>]
Get-Process -IncludeUserName -InputObject <System. Diagnostics.Process[]>
[<CommonParameters>]
ОПИСАНИЕ
The 'Get-Process' cmdlet gets the processes on a local or remote computer.
Without parameters, this cmdlet gets all of the processes on the local
computer. You can also specify a particular process by process name or
process ID (PID) or pass a process object through the pipeline to this
cmdlet.
By default, this cmdlet returns a process object that has detailed
information about the process and supports methods that let you start and
stop the process. You can also use the parameters of the 'Get-Process'
cmdlet to get file version information for the program that runs in the
process and to get the modules that the process loaded.
ССЫЛКИ ПО ТЕМЕ
Online Version: https://docs.microsoft.com/powershell/module/
microsoft.powershell.management/get-process?view=powershel1-5.l&WT .mc_id=
ps-gethelp
Debug-Process
Get-Process
Start-Process
Stop-Process
Wait-Process
ЗАМЕЧАНИЯ
To see the examples, type: "get-help Get-Process -examples".
For more information, type: "get-help Get-Process -detailed".
For technical information, type: "get-help Get-Process -full".
For online help, type: "get-help Get-Process -online"

We now additionally see a description of the Get-Process cmdlet and links to other related cmdlets. For detailed information, the Get-Help cmdlet should be run with the -Detailed or -Full options. In this case, detailed descriptions of each of the parameters supported by the analyzed cmdlet, various remarks, as well as examples of running this cmdlet with various parameters and arguments will be displayed (the -examples parameter allows you to see only examples separately). Example:

PS С:\Users\andrv> Get-Help Get-Process -Full
ИМЯ
Get-Process
ОПИСАНИЕ
Gets the processes that are running on the local computer or a remote
computer.
СИНТАКСИС
Get-Process [[-Name] <System.String[]>] [-ComputerName <System.String[]>]
[-FileVersionlnfo] [-Module] [<CommonParameters>]
Get-Process [-ComputerName <System.String[]>] [-FileVersionlnfo]
-Id <System.Int32[]> [-Module] [<CommonParameters>]
Get-Process [-ComputerName <System.String[]>] [-FileVersionlnfo]
-Inputobject <System.Diagnostics.Process[]> [-Module] [<CommonParameters>]
Get-Process -Id <System.Int32[]> -IncludeUserName [<CommonParameters>]
Get-Process [[-Name] <System.String[]>] -IncludeUserName
[<CommonParameters>]
Get-Process -IncludeUserName -Inputobject <System.Diagnostics.Process[]>
[<CommonParameters>]
ОПИСАНИЕ
The 'Get-Process' cmdlet gets the processes on a local or remote computer.
Without parameters, this cmdlet gets all of the processes on the local
computer. You can also specify a particular process by process name or
process ID (PID) or pass a process object through the pipeline to this
cmdlet.
By default, this cmdlet returns a process object that has detailed
information about the process and supports methods that let you start and 
stop the process. You can also use the parameters of the 'Get-Process' cmdlet
to get file version information for the program that runs in the process and
to get the modules that the process loaded.
ПАРАМЕТРЫ
-ComputerName <System.String[]>
Specifies the computers for which this cmdlet gets active processes.
The default is the local computer.
Type the NetBIOS name, an IP address, or a fully qualified domain name
(FQDN) of one or more computers. To specify the local computer, type the
computer name, a dot (.), or localhost.
This parameter does not rely on Windows PowerShell remoting. You can use
the ComputerName parameter of this cmdlet even if your computer is not
configured to run remote commands.
Требуется? false
Позиция? named
Значение по умолчанию Local computer
Принимать входные данные конвейера? True (ByPropertyName)
Принимать подстановочные знаки? false

As you can see, the description of the Name parameter provides information about five attributes. These attributes are inherent in most cmdlet parameters (Table 4.2).

Non-cmdlet related reference information

All available PowerShell Help topics can be seen using the Get-Help command

PS С:\Users\andrv> Get-Help *
Name Category Module
foreach Alias
Alias
Alias
Alias
where
ас
clc
cli
Alias
Alias
Alias
more
cd. .
cd\
ImportSystemModules
Pause
help
Function
Function
Function
Function
Function
Function
Add-History
Clear-History
Connect-PSSession
Debug-Job
Cmdlet Microsoft.PowerShell....
Cmdlet Microsoft.PowerShell....
Cmdlet Microsoft.PowerShell....
Cmdlet Microsoft.PowerShell....
about Aliases
about Alias Provider
about Arithmetic Operators
about Arrays
about Assignment Operators
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile

As you can see, the Get-Help cmdlet allows you to view help information not only about various cmdlets, but also about the syntax of the PowerShell language, about aliases, providers, functions and other aspects of the shell. A list of topics covered in the PowerShell Help can be seen using the following command:

PS С:\Users\andrv> Get-Help about_*
Name Category Module
about Aliases
about Alias Provider
about Arithmetic Operators
about Arrays
about Assignment Operators
about Automatic Variables
about Break
about Calculated Properties
about Certificate Provider
about Character Encoding
about CimSession
about Classes
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile
HelpFile

Thus, to read information, for example, about the use of arrays in PowerShell, you need to execute the following command:

PS С:\Users\andrv> Get-Help about_Arrays
ABOUT_ARRAYS
Short Description
Describes arrays, which are data structures designed to store collections
of items.
Long Description
An array is a data structure that is designed to store a collection of items.
The items can be the same type or different types.
Beginning in Windows PowerShell 3.0, a collection of zero or one object has
some properties of arrays.
Creating and initializing an array
To create and initialize an array, assign multiple values to a variable.

Note that the Get-He1p cmdlet displays the contents of the help section at the same time. The tap and he1p functions allow you to display help information on the screen (similar to the cmd.exe command of the interpreter), for example: tap about arrays.

A log of in-session commands

The system records information about all the commands we execute in the PowerShell shell in a special session log or command log, which makes it possible to reuse these commands without typing them completely on the keyboard. The session log is saved until you exit PowerShell.

To move back through the command log, press the <T> key. The first time you press this key, the command prompt displays the last command executed in the current session. Pressing the key again will display the penultimate command, etc. Once you get the command you want, you can edit it and then press <Enter> to execute the command. The key allows you to move forward using commands.

Instead of viewing all commands in the session log, you can view only commands that begin with certain characters. To do this, enter these initial characters in the command line and press the <F8> key.

In addition to keyboard shortcuts, PowerShell has special cmdlets for working with the command log. The command “Receive history” (aliases h, history and ghy) allows you to display the history of commands:

PS С:\> Get-History
Id CommandLine
1 cd с:
2 cd \
3 del -Recurse -Whatlf "C:\Program Files"
4 del -Recurse -Whatlf "C:\temp\*.*"
5 del -Whatlf "C:\temp\*.*"
6 Get-Alias del

By default, the last 32 commands are displayed with their serial numbers (Id column). The number of commands that are displayed can be changed using the -Count option. For example, the following command will display the last three commands:

PS С:\> Get-History -Count 3
Id CommandLine
5 del -Whatlf "C:\temp\*.*"
6 Get-Alias del
7 Get-History

From the session log, you can select commands that match a certain criterion. For this, the object pipeline procedure and the special Where-Object cmdlet are used (these topics are discussed in more detail in chapter 5). For example, to display all commands that contain the word del, you can run the following command:

PS С: \> Get-History | Where-Object {$_. CommandLine -like "*del*"}
Id CommandLine
3 del -Recurse -Whatlf "C:\Program Files"
4 del -Recurse -Whatlf "C:\temp\*.*"
5 del -Whatlf "C:\temp\*.*"
6 Get-Alias del

The list of commands obtained by Get-History can be exported to an external file in XML or CSV (comma-separated text file) format. To do this again, you need to use command pipelining and special cmdlets to export data to a specific format. For example, the following command saves the command history to the CSV file c:\history.csv: PS C:\> Get-History | Export-Csv c:\history.csv You can use the Add-History cmdlet to add commands to the session log (for example, to create a log that contains commands entered over multiple work sessions). For example, the following command will add commands stored in the c:\history.csv file to the session log: PS C:\> Import-Csv c:\history.csv | Add-History The invoke-History cmdlet (aliases -r, short for repeat or rerun. and ihy) allows you to re-execute commands from the session history, while commands can be specified by their sequence number or first characters, and also received through the pipeline from the Get-History cmdlet. Let’s give some examples.

Вызов последней команды:
PS С:\> Invoke-History
Вызов третьей команды по ее порядковому номеру:
PS С:\> Invoke-History -Id 3
или просто:
PS С:\> г 3
Вызов последней команды Get-Help:
PS С:\> Invoke-History Get-He
Вызов команд, полученных по конвейеру от командлета Get-History:
PS С:\> Get-History | Where-Object {$_. commandLine -like "*del*"} |
Invoke-History

Customize the appearance of the PowerShell command line

The appearance of the PowerShell command line (the color of the text and background, the font used, the degree of transparency of the window, etc.) depends on the settings of the terminal in which the shell is launched. If you are working in the standard console, then to configure the window parameters, you need to launch PowerShell, right-click on the window title bar (or any mouse button on the window icon) and select Properties from the context menu. A dialog box for changing the parameters of the PowerShell command window will open (Figure 4.5).

Fig. 4.5. Dialog box for configuring PowerShell window options

This window has several tabs (Settings, Font, Layout, Colors, and Terminal) that group controls that allow you to manage the respective categories of settings. We will not consider these parameters in detail, their purpose is quite obvious. When working in the new Windows terminal (wt.exe), the font size can be changed directly in the command line using the key combinations <Ctrl>+<+> (increase the font) and <Ctrl>+<-> (decrease the font). The appearance of each available profile in the terminal can be changed using the terminal settings on the Appearance tab (Fig. 4.6). Here you can choose a color scheme and font, set the shape of the cursor, set a background image, etc.

Fig. 4.6. Customize the appearance of the profile in the Windows terminal

The title of the command window

PowerShell makes it possible to configure various parameters of the command window (size, text and background color, title bar, etc.) directly from the shell. For this, you can use the Get-Host cmdlet, which by default displays information about the PowerShe11 shell itself (version, regional settings)

PS С:\Users\andrv> Get-Host
Name : ConsoleHost
Version : 5.1.19041.906
Instanceld : 13dac4f0-dbb5-4382-8627-e9ala03d2fde
UI :
Currentculture :
CurrentUICulture :
System.Management.Automation.Internal.Host...
ru-RU
ru-RU
PrivateData :
DebuggerEnabled :
IsRunspacePushed :
Microsoft.PowerShell.ConsoleHost+ConsoleColor...
True
False
Runspace : Systern.Management.Automation.Runspaces.Local...
Нам понадобится СВОЙСТВО UI (это объект .NET-Класса System. Management.
Automation.Internal.Host.InternalHostUserlnterface). В СВОЮ очередь, объект UI
имеет свойство Rawui, позволяющее получить доступ к параметрам командного
окна PowerShell. Для просмотра данных параметров выполним следующую команду:
PS С:\Users\andrv> (Get-Host) .UI .RawUI
Foregroundcolor
Backgroundcolor
CursorPosition
WindowPosition
CursorSize
BufferSize
WindowSize
MaxWindowSize
MaxPhysicalWindowSize
KeyAvailable
WindowTitle
Gray
Black
0,23
0, 0
25
120,39
120,39
120,39
1842,65
True
Windows PowerShell

Some properties of the RawUI object can be changed, thereby adjusting the corresponding properties of the command window. To do this, it is more convenient to save the RawUI object in a separate variable:

S C:\Users\andrv> $а= (Get-Host) .UI .RawUI

Now you can assign new properties. By default, the command window’s title bar displays Windows PowerShell. To change this title, you need to write a new value to the WindowTitIe property of the RawUI object:

PS C:\Users\andrv> $a.WindowTitle=”My command window”

Immediately after executing the last command, the title of the PowerShell window will be “My Command Window” (Figure 4.7).

Fig. 4.7. Changed the title of the PowerShell commands window

Command line prompt

Now let’s move on to configuring the command line. In PowerShell, this query is handled by the prompt function, which should return a single string. Let’s see, without going into details yet, what content this function has by default (displays ps symbols, then the path to the current directory and the > symbol). To do this, you can run the following command:

PS С:\Users\andrv> (Get-Itap function:prompt).Definition
"PS $ ($executionContext.Sessionstate.Path.CurrentLocation)$(’>’ *
($nestedPromptLevel +1))
# .Link
# https://go.microsoft.com/fwlink/?LinkID=225750
# .ExternalHelp System.Management.Automation.dll-help.xml

To change the prompt, you need to override the prompt function. For example, after running the following command, the prompt will consist of the directory path and the > symbol:

PS С:\Users\andrv> function prompt{"$(Get-Location)> "}
C:\Users\andrv>

As you can see, the appearance of the prompt changes immediately after the assignment of the new content of the prompt function In the prompt function, you can not only form a command line prompt, but also perform any other actions. For example, using the prompt function, you can solve the problem of displaying long paths to the current directory (such paths take up a lot of space when displaying the command line, and it becomes inconvenient to work). If you define the prompt function as in letter 4.1, then the path to the current directory will not be displayed in the prompt of the command line, but in the title of the command window (Fig. 4.8).

Code listing 4.1. Display of all script parameters

function prompt {
(Get-Host).UI.RawUI.WindowTitle="PS $(Get-Location)”
"PS > ”
}
Рис. 4.8. Вікно PowerShell, шлях до поточного каталогу як заголовок

Setting up user profiles

Previously, we looked at how you can customize some aspects of PowerShell to suit your needs. We learned how to create custom aliases and functions for frequently used cmdlets or other commands, define custom variables and drives, and modify the command line.

However, all these settings and changes will take effect only during the current session and will end after exiting the shell.

In order to save the changes, you need to create a so-called PowerShell profile and write in it all the commands that define aliases, functions, variables, etc. A profile is a script that will be automatically executed every time PowerShell is started. A well-designed profile can simplify PowerShell and operating system administration. In PowerShell, four different profiles can be defined for a user, located in the user’s home directory (the path to this directory is contained in the $Note variable) and in the PowerShell installation directory (the path to it is stored in the $PSHOME variable).

First, the profile can be saved in the file $PSHome\proflle.ps1. This profile applies to all users and shells.

Second, the profile can be located in the file $PSHome\Microsoft.PowerShell proflle.psl. This profile applies to all users, but only to one shell.

The third type of profile can be located in the file $Home\Documents\PowerShell\ proflle.psl. This profile applies only to the current user and to all shells.

Finally, the profile can be saved in the file $Home\Documents\WindowsPowerShell\ Microsoft.PowerShell_proflle.psl. This profile applies only to the current user and only to Microsoft.PowerShell.

Script execution policies

The PowerShell execution policy determines whether PowerShell scripts can be executed on a particular computer (including loading custom script profiles that are automatically executed when the shell is started) and, if so, whether they must be digitally signed. Possible PowerShell execution policies are described in Table 4.3 (similar information can be obtained in PowerShell using the Get-Help about sign command).

You can find out which execution policy is active using the Get-ExecutionPolicy cmdlet:

Get-ExecutionPolicy:
PS С:\> Get-ExecutionPolicy
Restricted

By default, PowerShell has a restricted access policy that prevents any scripts from running while enabling user profiles.

Use the Set-ExecutionPolicy cmdlet to change the execution policy. Policy settings are stored in the system registry, so you need to run PowerShell as an administrator to change them. For example, to set the RemoteSign execution policy, run the following command:

Set-ExecutionPolicy RemoteSigned

Let’s check the current policy again:

PS С:\> Get-ExecutionPolicy
RemoteSigned

Now let’s end the PowerShell session and start the shell again. This time, you will not receive any error messages, the user profile prompt function should work correctly, and the path to the current directory will appear in the title bar of the PowerShell command window (see Figure 4.8).

Results

  • The ability to edit text in PowerShell depends on the terminal you are using.

  • PowerShell supports autocompletion when entering file and directory paths, as well as command and variable names.

  • Use the Get-He1p cmdlet to get help with commands and other aspects of PowerShell.

  • A PowerShell command-line session can be registered—commands and their output will be automatically saved to an external file.

  • The appearance of the PowerShell command line depends on the settings of the terminal in which the shell is running.

  • Additional modules (PSReadLine, posh-git, 0h Mu Posh) extend command line management and design.

  • When PowerShell starts, it automatically executes profile scripts where you can define the aliases, functions, and variables you want.

  • The execution modes of PowerShell scripts depend on the set policy. The execution policy can be found using the Get-ExecutionP01icy cmdlet, and it can be changed using the Set-ExecutionP01icy function.

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.