Managing Command Output in PowerShell is a complete guide for anyone who wants to work efficiently with the PowerShell shell and confidently manage command output. Using commands in PowerShell allows you to interact with the operating system, perform tasks, and obtain results. However, sometimes the output can be congested or difficult to parse. In this tutorial, we’ll look at different approaches to managing command output, such as filtering, sorting, saving results to a file, and using output streams. You will learn about the various options and functions that will allow you to easily find the information you need, control the output and save the data for use.
Regardless of your experience with PowerShell, this guide will help you streamline your work with commands, make it easier to analyze the results, and increase your productivity when working with this powerful command shell. While working in the PowerShell shell, we have not yet thought about how the system forms text lines that are displayed on the screen as a result of the execution of one or another command (recall that PowerShell cmdlets return .NET objects, which, as a rule, do not know how to display themselves on the screen). In fact, PowerShell has a database (set of XML files) that contains default formatting modules for various types of .NET objects. These modules determine which object properties are displayed during output and in which format: list or table. The formatting modules are located in the directory where PowerShell is installed (the path to this directory is stored in the $pshome environment variable), you can view their list using the following command: PS C:\> Get-Childltam $PSHCME/*format*
While working in PowerShell, we have not yet thought about how the system generates lines of text that are displayed as a result of executing one or another command (recall that PowerShell cmdlets return . NET objects that usually cannot display themselves on the screen).
Basically, PowerShell has a database (a set that contains default formatters for various . NETTO-06EkТ0B. These modules determine which properties of the object are displayed at the output and in which format: lists and tables. Formatters are located in the directory where PowerShell is installed (the path to this directory is stored in the $PSHOME environment variable), you can view their list using the following command:
PS С:\> Get-Childltam $PSHCME/*format* Каталог: С:\Windows\System32\WindowsPowerShell\vl.О Mode LastWriteTime Length Name -а--- 07.12.2019 12:10 12825 Certificate.format.pslxml -а--- 07.12.2019 12:10 4994 Diagnostics.Format.pslxml -а--- 07.12.2019 12:10 138013 DotNetTypes.format.pslxml -а--- 07.12.2019 12:10 10112 Event.Format.pslxml -а--- 07.12.2019 12:10 25306 FileSystem.format.pslxml -а--- 07.12.2019 12:10 91655 Help.format.pslxml -а--- 07.12.2019 12:10 138625 HelpV3.format.pslxml -а--- 07.12.2019 12:10 206468 PowerShellCore.format.pslxml -а--- 07.12.2019 12:10 4097 PowerShellTrace.format.pslxml -а--- 07.12.2019 12:10 8458 Registry.format.pslxml -а--- 07.12.2019 12:10 16598 WSMan.Format.pslxml
When an object reaches the end of the pipeline, PowerShell determines its type and looks for it in the list of objects that have a formatting rule set. If this type is found in the list, the corresponding form is applied to the object; if not, PowerShell simply displays the properties of this . NETTO-06RKTA.
You can also explicitly set formatting rules for cmdlets and, like other console programs, redirect that data to a file, printer, or empty device.
In traditional shells, commands and utilities format the output themselves. Some commands (for example, dir in the cmd.exe interpreter) allow you to customize the output format using special key parameters.
In PowerShell, the result is formatted with four special format cmdlets (Table 6.1). This makes learning easier because you don’t have to remember the tools and formatting options for other commands (the rest of the cmdlets don’t format the output).
As noted earlier, if none of the Format cmdlets is explicitly specified, the default formatter is used, which is determined by the type of data being displayed. For example, when running the Get-Service cmdlet, the default output is a table with three columns (Status, Name, and Disp1ayName):
DisplayName)* PS С:\> Get-Service Status Name DisplayName Stopped Alerter Running ALG Stopped AppMgmt Stopped aspnet state Running Ati HotKey Poller Running Audiosrv Running BITS Оповещатель Служба шлюза уровня приложения Управление приложениями ASP.NET State Service Ati HotKey Poller Windows Audio Фоновая интеллектуальная служба пер... Running Browser Обозреватель компьютеров Stopped cisvc Служба индексирования Stopped ClipSrv Сервер папки обмена Stopped clr optimizatio.. . .NET Runtime Optimization Service v Stopped COMSysApp Системное приложение COM+ Running CryptSvc Службы криптографии Running DcomLaunch Запуск серверных процессов DCOM Running Dhcp DHCP-клиент
To change the output format, you must pass it to the appropriate Fornat cmdlet. For example, using the Format-List cmdlet, the following command will list the following commands:
PS С:\> Get-Service | Format-List Name DisplayName Status DependentServices ServicesDependedOn CanPauseAndContinue : Alerter : Оповещатель : Stopped : {} : {LanmanWorkstation} : False CanShutdown : False CanStop ServiceType : False : Win32ShareProcess Name DisplayName Status DependentServices ServicesDependedOn CanPauseAndContinue CanShutdown : ALG : Служба шлюза уровня приложения : Running : {} : {} : False : False CanStop ServiceType : True : Win320wnProcess
As you can see, when using the list format, more information about each service is displayed than the table format (instead of three columns of data for each service, the list format displays nine rows of data). However, this does not mean that the format list cmdlet receives additional information about the services. This information is contained in the objects returned by the Get-Service command, but the default Fomat-Tab1e cmdlet discards it because it cannot display more than three columns. When formatting the output using the Format-List and Fonnat-Tab1e cmdlets, you can specify the names of the object properties to be displayed (recall that the list of object properties can be viewed in the Get-Member cmdlet). Example:
PS С:\> Get-Service | Format-List Name, Status, CanStop Name : Alerter Status : Stopped CanStop : False Name : ALG Status : Running CanStop : True Name : AppMgmt Status : Stopped CanStop : False Вывести все имеющиеся у объектов свойства можно с помощью параметра *, например: PS С:\> Get-Service Format-List * Name CanPauseAndContinue CanShutdown CanStop DisplayName Dependentservices MachineName ServiceName ServicesDependedOn ServiceHandle Status ServiceType Site Container Name CanPauseAndContinue CanShutdown Alerter False False True Оповещатель {} Alerter {LanmanWorkstation} SafeServiceHandle Running Win32ShareProcess : ALG : False : False
There are several cmdlets in the PowerShell shell that you can use to control the output. These cmdlets start with the word Out, and you can see their list like this:
PS С:\> Get-Command out-* | Format-Table Name Name Out-Default Out-File Out-GridView Out-Host Out-Null Out-Printer Out-String
By default, output is passed to the 0ut-Defau1t cmdlet, which in turn delegates all string display work to the 0ut-Host cmdlet. To understand this mechanism, it should be kept in mind that the architecture of PowerShell implies a distinction between the shell kernel itself (the command interpreter) and the host application that uses that kernel. In principle, any application that implements a number of special interfaces that allow you to correctly interpret the information received from PowerShell can act as a host. In our case, the host is a console window (terminal) in which we work with the shell, and the 0utHost cmdlet sends output information to this window.
The -Paging parameter of the Out-Host cmdlet, similar to the command of the cmd.exe interpreter, allows you to organize page-by-page display of information, for example:
PS С:\> Get-Help Get-Process -Full | Out-Host -Paging ИМЯ Get-Process ОПИСАНИЕ Отображает процессы, выполняющиеся на локальном компьютере. СИНТАКСИС Get-Process [[-name] <string[]>] [<CommonParameters>] <ПРОБЕЛ> следующая страница; <CR> следующая строка; Q выход
As mentioned, PowerShell supports redirecting the standard output stream of commands to text files using the standard > and >> operators. For example, the following command will map the contents of the root directory c:\ to the text file d:\dir c.txt (if this file exists, it will be overwritten):
PS C:\> реж. C:\ > d:\dir c.txt
If you want to redirect the output of the command to a file in append mode (while preserving the previous contents of this file), you should use the >> operator:
PS DXR з:\ >> d: \dxr c.txt
In addition to the > and >> redirection operators, PowerShell also has a cmdlet called 0utFile that also allows you to direct output to a text file instead of a console window. At the same time, the 0ut-Fi1e cmdlet has several additional parameters with which you can more flexibly control the output: specify the file encoding type, specify the length of the output lines in characters, and select the file overwriting mode (Table 6.2).
For example, the following command will save a detailed version of the built-in help for the Windows-encoded Get-Process cmdlet to the help.txt file:
PS С:\Users\andrv> Get-Help Get-Process -Detailed | Out-File -FilePath .\help.txt -Encoding "Default"
You can print data directly to the printer using the Out-Printer cmdlet. In this case, printing can be performed either on the default printer (no special parameters are required for this), or on an arbitrary printer (in this case, the short name of the printer must be specified as the value of the -Name parameter). Example:
PS C:\script> Get-Process | Out-Printer -Name "Xerox Phaser 3500 PCL 6"
Use the 0ut-Nu11 cmdlet to cancel any input. This can be useful for suppressing the display of unnecessary information received as a side effect of command execution. For example, when creating a directory with the mkdir command, its contents are displayed:
PS С:\> mkdir klop Каталог: Microsoft.PowerShell.Core\FileSystem::С:\ Mode LastWriteTime Length Name d--- 26.05.2020 15:01 klop Если мы не желаем видеть эту информацию, то результат выполнения команды mkdir нужно передать по конвейеру командлету Out-Null: PS С:\> mkdir klop | Out-Null PS C:\> Как видим, в этом случае никаких сообщений на экран не выводится.
With the help of the 0ut-GridView cmdlet, as with Fornat-Table, you can display data in tabular form, but not in the same console window, but in a separate dialog box with a graphical interface.
For example, run the following command:
ps C: \> Get-Process Out-GridView
At the same time, information about the processes will be available in a separate window (Fig. 6.1)
The title bar of this window displays the executed PowerShell command, and if necessary, you can change the title by specifying the -Tit1e option:
PS C:\> Get-Process | Out-GridView -Title “Processes”
The displayed table can be sorted by the values of any column by clicking on its name. You can also filter rows according to various conditions using the filter designer (Fig. 6.2).
The tabular view of the data generated by Out-GridView is interactive and can be changed directly in the table itself. Moreover, the resulting set of rows obtained by sorting, filtering, and selection can be returned to PowerShell again by clicking OK and sent further down. To do this, you need to specify -PassThru. Example:
PS С:\> Get-Process 1 Out-GridView -Title "Процессы" -PassThru | Format-Table Id, ProcessName
Id ProcessName 836 wininit 12412 WINWORD
In this example, the rows (objects) from the next window are passed to the Format-Table cmdlet
The rows to be returned to the PowerShell pipeline from the dialog must be selected in the table view (by default, only the first row is returned).
Standard combinations are supported here:
<Ctrl>+<A> to enter all lines;
Hold <Shift> and the up or down arrows to select a contiguous range of lines;
Hold <Ctrl> and click to add individual lines
PowerShell has a standard cmdlet called ConvertTo-Htm1 that you can use to display the output of your commands. For example, let’s use Get-PSDrive to get a list of PowerShell drives and convert the list to HTML:
PS С:\Users\andrv> Get-PSDrive I ConvertTo-Html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN” "http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> 118 Часть I. Знакомимся с PowerShell <head> <title>HTML TABLE</title> </headxbody> <table> <colgroupxcol/xcol/xcol/xcol/xcol/xcol/xcol/xcol/xcol/xcol/x/colgroup> <trxth>Used</thxth>Free</thxth>CurrentLocation</thxth>Name</thxth>Provider </thxth>Root</thxth>Description</thxth>MaximumSize</thxth>Credential</th> <th>DisplayRoot</thx/tr> <trxtdx/tdxtdx/tdxtdx/tdxtd>Alias</tdxtd>Microsoft. PowerShell. Core\ Alias</tdxtdx/tdxtd>HwcK, содержащий представление псевдонимов, сохраненное в состоянии сеанса. </tdxtdx/tdxtd>System.Management .Automation. PSCredential</tdxtdx/tdx/tr> <trxtdx/tdxtdx/tdxtdx/tdxtd>WSMan</tdxtd>Microsoft.WSMan. Management\ WSMan</tdxtdx/tdxtd>KopeHb хранилища конфигурации WsMan.</tdxtdx/td> <td>System. Management .Automation. PSCredential</tdxtdx/tdx/tr> </table> </bodyx/html>
As you can see, the output is a correct HTML document with a table designed using the <tabie> tag. This output can be sent to an HTML file and opened in a browser (Fig. 6.4) using the invoke-item cmdlet:
PS С:\Users\andrv> Get-PSDrive | ConvertTo-Html | Out-File psdrives.html PS C:\Users\andrv> Invoke-Item .\psdrives.html
The -As List parameter allows you to change the appearance of the table – the properties of each object will be formatted as a list (Fig. 6.5), as when formatting the output using Fomat-List:
PS С:\Users\andrv> Get-PSDrive | ConvertTo-Html -As List | Out-File psdrives. html PS C:\Users\andrv> Invoke-Item .\psdrives.html
With the help of additional parameters, you can set the header text before and after the table:
PS С:\Users\andrv> Get-PSDrive | ConvertTo-Html -Title ’’Отчет о дисках PowerShell" -PreContent "<р>Текст до таблицы</р>" -PostContent "Текст после таблицы" | Out-File .\psdrives.html
При необходимости к формируемому HTML-документу можно подключить внешний CSS-файл, путь к которому указывается в качестве значения параметра -cssUri. Если в convertTo-HTML указан параметр -Fragment, то в HTML-разметке будет сгенерирована только таблица с данными (тег <tabie>): PS С:\Users\andrv> Get-PSDrive | ConvertTo-Html -Fragment <table> <colgroupxcol/xcol/xcol/xcol/xcol/xcol/xcol/xcol/xcol/xcol/x/colgroup> <trxth>Used</thxth>Free</thxth>CurrentLocation</thxth>Name</thxth>Provider </thxth>Root</thxth>Description</thxth>MaximumSize</thxth>Credential</th> <th>DisplayRoot</thx/tr> <trxtdx/tdxtdx/tdxtdx/tdxtd>Alias</tdxtd>Microsoft. PowerShell. Core\ Alias</tdxtdx/tdxtd>JJncK, содержащий представление псевдонимов, сохраненное в состоянии сеанса. </tdxtdx/tdxtd>System.Management .Automation. PSCredential </tdxtdx/tdx/tr> </table>
In addition to the standard 0utput stream through which objects are passed from cmdlet to cmdlet, PowerShell supports several other streams.
The presence of several continuous chains does not clutter the main flow with errors or other additional messages – cmdlets receive only the necessary structured objects as input.
You can write data to different threads using the corresponding cmdlets using the Write verb: Write-Output, Write-Error, Write-Warning, WriteVerbose, Write-Debug, and Write-Information.
For example, let’s write a new message in the error stream:
PS С:\Users\andrv> Write-Error -Message "Произошла ошибка" Write-Error -Message "Произошла ошибка" : Произошла ошибка + Categoryinfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorld : Microsoft.PowerShell.Commands.WriteErrorException
This automatically generated an object with error information and placed it in the error stream (we’ll talk more about error detection and handling in PowerShell in Chapter 10). Error information from the error stream is also displayed and highlighted in red.
Information from the Verbose stream is displayed in the console and is highlighted in yellow only if the -Verbose parameter is specified when calling the command:
PS С: \Users\andrv> Write-Verbose -Message "Сообщение из потока Verbose" PS С:\Users\andrv> Write-Verbose -Message "Сообщение из потока Verbose" -Verbose ПОДРОБНО: Сообщение из потока Verbose Поведение (в частности, режим вывода на экран сообщений) команд write-* зависит от значений нескольких системных переменных: PS С:\Users\andrv> $ErrorActionPreference Continue PS C:\Users\andrv> $DebugPreference SilentlyContinue PS C:\Users\andrv> $VerbosePreference SilentlyContinue PS C: \Users\andrv> $InforrnationPreference SilentlyContinue
If the value of the variable Si1entlyContinue, then the information from the corresponding stream is not duplicated on the screen. For additional PowerShell streams, redirection to a file or to the standard output stream 0utput is also supported.
You can redirect data from a stream to a file using the same > and >> operators, preceded by a numeric stream number. Example:
PS С:\Users\andrv> Write-Error -Message "Произошла ошибка" 2> error.txt PS С:\Users\andrv> Get-Content .\error.txt Write-Error -Message "Произошла ошибка" 2> error.txt : Произошла ошибка + Categoryinfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorld : Microsoft.PowerShell.Commands.WriteErrorException PS C: \Users\andrv> Write-Warning -Message "Сообщение из потока Warning" 3> l.txt PS C:\Users\andrv> Get-Content .\l.txt Сообщение из потока Warning Также с помощью оператора *> можно перенаправить в один файл все данные из всех потоков. Например, выполним блок кода, в котором идет запись в потоки Output, warning и Error, и перенаправим данные из всех этих потоков в файл streams.txt: PS С:\Users\andrv> & { Write-Output "Данные из Output" » Write-Warning "Данные из Warning" » Write-Error "Данные из Error" » } *> streams.txt PS С:\Users\andrv> Get-Content .\streams.txt Данные из Output Данные из Warning Write-Output "Данные из Output" Write-Warning "Данные из Warning" Write-Error "Данные из Error" : Данные из Error строка:1 знак:1 + & { Write-Output "Данные из Output" + Categoryinfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorld : Microsoft.PowerShell.Commands.WriteErrorException
You can redirect data from a stream numbered n n to the standard output stream 0utput, which is numbered 1, using For example, let’s try saving data from a Verbose stream:
PS С:\Users\andrv> $message = Write-Verbose -Message "Подробное сообщение" -Verbose ПОДРОБНО: Подробное сообщение Проверим значение переменной $message: PS С:\Users\andrv> $message Как видим, в $message ничего не записалось, т. к. оператор присваивания получает данные ИЗ ВЫХОДНОГО потока Output, а не ИЗ потока Verbose. Перенаправим теперь поток verbose с номером 4 в выходной поток output (номер 1): PS С:\Users\andrv> $message = Write-Verbose -Message "Подробное сообщение" -Verbose 4>&1 После ЭТОГО переменная $message будет иметь ТИП System.Management.Automation. verboseRecord, в ней будет содержаться наше сообщение: PS С:\Users\andrv> $message ПОДРОБНО: Подробное сообщение PS С:\Users\andrv> $message.getType().fullName System.Management.Automation.VerboseRecord
PowerShell uses an internal formatting system that determines the appearance and content of object information that is displayed on the screen. Formatting rules can be set explicitly using cmdlets
By default, the data is displayed on the screen, using the 0ut-* cmdlets, the output can be redirected to a file, to a printer, or to an empty device. Use the Out-GridView cmdlet to display the data table in a separate GUI dialog box.
The output of the commands can be formatted with ConvertTo-HTM1.
PowerShell supports several independent threads to display additional information on them that is not needed in the main thread that provides the flow of objects along the pipeline. Data from these additional streams can be redirected to a file or to the standard output stream 0utput.
Thanks to our team of volunteers for providing information from open sources.