Managing automation processes, services, and servers with PowerShell is a fundamental capability for any IT and cybersecurity professional. PowerShell, developed by Microsoft, is a powerful scripting and automation tool that allows you to monitor and manage processes and services on computers and servers. In this article, we look at how to use PowerShell to monitor, start, stop, and configure processes and services, as well as to manage servers and their configuration.
You will learn to use a variety of commands and scripts to effectively manage your IT infrastructure. This article will also provide you with information on creating scripts to automate tasks such as regularly updating servers, monitoring system health, and fixing errors. You’ll learn how to use PowerShell to collect system data, automate routine tasks, and improve the overall productivity of IT operations. In this section, we’ll look at issues related to running PowerShell with two important components of the Windows operating system: running processes and services running in the background.
The main graphical tool for managing processes on the local machine is the Windows task manager (to start the task manager, you can press the key combination <Ctrl>+<Shift>+<Esc>), which displays information
For example, if you want to know what is happening, you can stop them and set the execution priority (Fig. 13.1).
Windows also has the console utilities task1ist (view a list of processes running on a local or remote computer) and taskki11 (stop a process):
PS С:\Users\andrv> tasklist /? TASKLIST [/S <система> [/U <Ім'я користувача> [/Р [<пароль>]]]] [/М [<модуль>] | /SVC | /V] [/FI <фильтр>] [/F0 <формат>] [/NH] Опис: Відображає список процесів, які зараз виконуються на локальному або віддаленому комп'ютері. PS С:\Users\andrv> taskkill /? TASKKILL [/S <система> [/U <пользователь> [/P [<пароль>]]]] { [/FI <фильтр>] [/PID <процесс> | /1М <образ>] } [/Т] [/F] Опис: Завершує процес за його ID (PID) або ім'ям образу.
Let’s see how PowerShell can handle some typical process tasks.
In PowerShell, you can use the GetProcess cmdlet to get a list of running processes. If you run this cmdlet with no parameters, you will see information about all running processes:
PS С:\> Get-Process Handles NPM(K) РМ (К) WS (К) VM(M) CPU(s) Id ProcessName 109 5 1128 7 92 32 0.06 1360 alg 506 6 2308 3604 29 20.34 628 csrss 67 3 832 436 29 1.52 1736 ctfmon 553 17 17220 11992 94 69.16 1164 explorer 33 2 3280 400 35 2.41 3192 Far
Each process has an object of type System. Diagnostics. Process; By default, the Get-Process cmdlet displays several properties of these objects (Table 13.1).
With the -Name option (this is the default option), you can display information about one or more processes with specific names (and the names can use wildcards).
In 2014, the Netherlands For example, the following command will list all processes whose names begin with the letter s:
PS С:\> Get-Prooess s* Handles NPM (К) PM (К) WS (K) VM(M) CPU(s) Id ProcessName 106 2 380 32 11 0.03 1880 scardsvr 134 4 1876 200 88 0.11 3640 sdlaunch 267 6 1504 1236 46 3.67 696 services 19 1 164 52 4 0.06 560 smss 71 2 1820 588 30 0.14 1352 SOUNDMAN 297 6 6924 1768 54 5.05 1304 spoolsv 134 3 1424 824 33 0.16 876 svchost 314 13 1768 1280 36 0.75 944 svchost 1185 45 12124 6532 83 14.59 1040 svchost 59 3 1124 740 27 1.23 1076 svchost 224 7 2356 788 38 0.27 1204 svchost 130 4 2392 1324 35 0.81 1952 svchost 517 0 0 52 1 26.75 4 System
To sort or filter the list of processes, use the Sort-Object, Where-Object, and Se1ect-Object cmdlets as usual. For example, the following instruction pipeline displays the five processes that consume the most CPU time:
PS С:\> Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 Handles NPM(K) PM(K) WS (K) VM(M) CPU(s) Id ProcessName 619 19 21044 23156 110 171.19 1164 explorer 790 50 59228 11788 191 93.17 1520 kavsvc 476 14 10320 111'20 129 88.25 2860 OUTLOOK 448 19 61204 23412 165 83.59 3884 wjview 411 12 9780 8920 250 61.95 3484 WINWORD
To view complete information about one or more processes, you can use the Format-List cmdlet, displaying all properties of the System object. Diagnostics. Process. Example:
PS С:\> Get-Process outlook | Format-List *
To get a list of processes on remote machines, specify their names or IP addresses as the -deleterName value.
System objects. Diagnostics. The Process returned by the Get-Process cmdlet has a Modules property that contains a list of dynamic libraries used by the corresponding processes. To view this list, you can process these objects with the cmdlet Select-Object With -ExpandProperty. For example, the following command pipeline lists all dynamic libraries used by PowerShell (the process named powershell)
PS С:\> Get-Process powershell | Select-Object -expandproperty modules | Format-Table Size(K) ModuleName FileName 452 powershell.exe C:\WINDOWS\System32\WindowsPowerShell\vl.OXpowershell.exe 2004 ntdll.dll C:\WINDOWS\SYSTEM32\ntdll.dll 756 KERNEL32.DLL C:\WINDOWS\System32\KERNEL32.DLL 2848 KERNELBASE.dll C:\WINDOWS\System32\KERNELBASE.dll 632 msvcrt.dll C:\WINDOWS\System32\msvcrt.dll 820 OLEAUT32.dll C:\WINDOWS\System32\OLEAUT32.dll 628 msvcp_win.dll C:\WINDOWS\System32\msvcp_win.dll 1024 ucrtbase.dll C:\WINDOWS\System32\ucrtbase.dll 116 ATL.DLL C:\WINDOWS\SYSTEM32\ATL.DLL 3412 combase.dll C:\WINDOWS\System32\combase.dll
To stop a process on the local machine, you can use the Stop-Process cmdlet, which has the alias ki11. By default, the Id parameter is used, which requires specifying the ID of the process to be stopped (recall that you can find the process ID using the Get-Process cmdlet). For example, the following command will stop the process with ID 764:
PS С:\> Stop-Process 764
To stop a process with a specific name, use the -Name parameter of the Stop-Process cmdlet. For example, the following command will kill all processes named notebook:
PS С:\> Stop-Process -Name notepad
The -Confinn option of the Stop-Process cmdlet enables confirmation mode when processes are stopped. At the same time, both the name and the identifier of the stopped process are displayed on the screen, for example:
PS С:\Users\andrv> Stop-Process -Name notepad -Confirm Подтверждение<br />Вы действительно хотите выполнить это действие?<br />Выполнение операции ’’Stop-Process" над целевым объектом "notepad (2812)".<br />[Y] Да - Y [А] Да для всех - A [N] Нет - N [L] Нет для всех - L [S]<br />Приостановить - S [?] Справка<br />(значением по умолчанию является "Y"):Y<br />Подтверждение<br />Вы действительно хотите выполнить это действие?<br />Выполнение операции "Stop-Process" над целевым объектом "notepad (13984)".<br />[Y] Да - Y [А] Да для всех - A [N] Нет - N [L] Нет для всех - L [S]<br />Приостановить - S [?] Справка<br />(значением по умолчанию является "Y"):Y<br />
By default, the Stop-Process cmdlet does not skip objects that correspond to processes stopped further down the pipeline, so nothing is displayed on the screen. To stop processes from outputting information, specify the -PassThru option, for example:
PS С:\> Stop-Process -Name notepad -PassThru Handles NPM(K) PM (К) WS(K) VM(M) CPU(s) Id ProcessName 26 2 624 2172 24 2224 notepad
To run a process from PowerShell, you can simply specify the path to the appropriate executable, for example:
PS С: \> С: \WINDOWS\system32\notepad.ехе
You can also invoke the process using the Invoke-Item cmdlet, specifying the path to the desired file as an argument. The -Confinn option allows the process to run only after the user confirms:
PS С:\> Invoke-item C:\WINDOWS\system32\notepad.exe -Confirm Подтверждение<br />Вы действительно хотите выполнить это действие?<br />Выполнение операции "Вызов элемента" над целевым объектом "Элемент:<br />С:\WINDOWS\system32\notepad.exe".<br />[Y] Да - Y [А] Да для всех - A [N] Нет - N [L] Нет для всех - L [S]<br />Приостановить - S [?] Справка<br />(значением по умолчанию является "Y"):Y
However, the Invoke-Item cmdlet does not return an object that corresponds to the running process, so we cannot programmatically determine, say, the process’s system-assigned ID. Therefore, it is better to start processes on the local machine using a special Start-Process cmdlet. The path to the executable file or script to run is specified in the -FilePath parameter:
PS С:\Users\andrv> Start-Process -FilePath notepad.exe
The parameters of the Start-Process command allow you to pass arguments to the starting process, redirect its input and output streams, specify the account and determine the type of window for the process, and so on.
By default, Start-Process only starts the process without returning anything. If you want to return an object that corresponds to the new process, you should use the -PassThru switch:
PS С:\Users\andrv> $prooess = Start-Process -FilePath notepad.exe -PassThru PS C:\Users\andrv> $process.GetType().FullName System.Diagnostics.Process
Note that with the help of Start-Process you can not only launch executable files, but also perform actions related to other types of files. For example, let’s create a text file l.txt and start printing it by executing the Start-Process command with the Print action:
PS С:\Users\andrv> "File content" > l.txt PS C:\Users\andrv> Start-Process -FilePath .\l.txt -Verb Print
Let’s also look at the Create( ) method of the WMI-kJIacca Win32 Process, which can be used to start processes on both the local and remote computers. This method is a constructor of the Win32 Process class and can be called using the [vniC1ass] specifier. For example, let’s launch “Notepad”:
PS С:\> $а = ([wmiClass] "win32_process").Create("notepad.exe")
Using the Get-Merrber cmdlet, let’s see what properties the object stored in the $a variable has:
PS С:\> $а | Get-Member TypeName: System.Management.ManagementBaseObject#\__ PARAMETERS Name MemberType Definition PSComputerName AliasProperty PSComputerName = SERVER Processid Property uint32 Processid {get;set;} ReturnValue Property uint32 ReturnValue {get;set;} __ CLASS Property string CLASS {get;set;} __ DERIVATION Property string}] DERIVATION {get;set;} __ DYNASTY Property string DYNASTY {get;set;} __ GENUS Property int GENUS {get;set;} __ NAMESPACE Property string NAMESPACE {get;set;} __ PATH Property string PATH {get;set;} PROPERTY COUNT Property int PROPERTY_COUNT {get;set;} __ RELPATH Property string RELPATH {get;set;} __ SERVER Property string SERVER {get;set;} SUPERCLASS Property string SUPERCLASS {get;set;}
As you can see, the ProcessId property is available to us, which stores the ID of the running process.
System. Diagnostics. A process has a PriorityC1ass method set that allows you to change the priority of the process. The parameter of this method must be one of the following strings: Normal, Idle, High, RealTime, BelowNormal, AboveNormal. For example, let’s start a new instance of Notepad and use the getPriorityC1ass method to check the current priority of this process:
PS С:\Users\andrv> $b = Start-Process -FilePath notepad.exe -PassThru PS С:\> $b.get_PriorityClass() Normal Підвищимо тепер пріоритет до високого: PS С: \> $b. set_PriorityClass (’’High") PS С:\> $b.get_PriorityClass() High
In System objects. Diagnostics. A process that responds to running processes has a Responding property that evaluates to False if the process is not responding. To kill all non-responsive programs, select them from the crowd with the Where-Object cmdlet, and then stop them with the Stop-Process cmdlet:
PS С:\> Get-Process | Where-Object -not Responding | Stop-Process
In the Windows operating system, a service is a process that runs on a computer in the background to perform certain actions in response to user requests. For example, a web server service runs in the background waiting for NTTR requests from clients. When such a request is received, the service responds by sending the requested file to the client or performing a certain action. The content of the services depends on the version of the operating system and the applications installed on it.
The main tool for administering services in graphical mode on a local computer is the services console, which is located in the “Administration” group of the control panel (see Fig. 13.2).
The Computer Management Console is used as a utility that can be used to manage services on both local and remote machines. Windows also includes standard cmd.exe shell utilities for service administration: net start and net stop.
Let’s look at ways to use PowerShell to solve some common maintenance tasks.
To get a list of services registered on the local computer, use the Get-Service cmdlet:
PS С:\> Get-Service Status Name DisplayName Running Alerter Оповещатель Running ALG Служба шлюза уровня приложения Stopped AppMgmt Управление приложениями Stopped aspnet state ASP.NET State Service Running AudioSrv Windows Audio Stopped BITS Фоновая интеллектуальная служба Stopped Browser Обозреватель компьютеров Stopped cisvc Служба индексирования Stopped ClipSrv Сервер папки обмена
As you can see, the name of the service (column Name), its short name (column Disp1ayName) and status (column Status) are displayed by default.
The Get-Service cmdlet has -Name and -Disp1ayName options that support templates. For example, the following command lists services whose names begin with win:
If you want to display only those services that are currently running, you need to filter the objects, the value of the Status property is the string Runing:
PS С:\> Get-Service | Where-Object Status -eq "Running”
To view the services registered on a remote computer, you must specify its name as the value of the -ComputerName parameter.
The local service can be stopped using the Stop-service cmdlet (PowerShell must be run as an administrator). The -Name parameter specifies the name of the service to be stopped (wildcards can be used here), the -Force parameter allows you to stop the specified service along with all services that depend on it.
For example, the following command will stop the LanmanServer service (which supports online file and printer sharing) and all services that depend on it:
PS С:\> Stop-Service -Name LanmanServer -Force
By default, the stop-Service cmdlet does not skip objects that correspond to services stopped further down the pipeline, so nothing is displayed on the screen. To stop services with information output, you need to specify the -PassThru option, for example:
PS С:\> Stop-Service -Name LanmanServer -Force -PassThru Status Name DisplayName Stopped LanmanServer Сервер
You can use the Suspend-Service cmdlet to suspend one or more services whose names are specified as the value of the -Na•ne parameter. When a service is suspended (temporarily stopped), the service continues to run, but its actions are suspended until a resume command is received (see the next section).
It is worth considering that not every service can be suspended. In System objects. ServiceProcess . SernceContr011er corresponding to services has a boolean property called CanPauseAndContinue that is set to True if the service can be paused. The following command will stop all eligible services:
PS С:\> Get-Service | Where-Object {$_•CanPauseAndContinue} | Suspend-Service - PassThru Status Name DisplayName Paused Irmon Монитор инфракрасной связи Paused lanmanserver Сервер Paused lanmanworkstation Рабочая станция Paused Schedule Планировщик заданий Paused seclogon Вторичный вход в систему Paused ShellHWDetection Определение оборудования оболочки Paused TapiSrv Телефония Paused winmgmt Инструментарий управления Windows
You can start a service on the local computer using the StartService cmdlet. The value of the -Name parameter is the name of the service to start. As with previous *-Service cmdlets, no message is displayed after the service is started; To fix the situation, you can use the -PassThru option. For example, the following command starts the LaTanServer service and displays information about it:
PS С:\> Start-Service -Name LanmanServer -PassThru Status Name DisplayName Running Spooler Диспетчер очереди печати
The restart service cmdlet restarts (that is, stops and starts) services that are specified as the value of the -Name parameter or that have been passed in from other cmdlets. For example, the following command pipeline restarts all network services whose name begins with the string net: PS using:
PS С:\> Get-Service -Name net* | Restart-Service
PowerShell has a cmdlet called Set-Service that allows you to edit some service settings on a local or remote computer:
DisplayName (DisplayName parameter);
Description (Description parameter);
Startup type (Parameter StartupType), possible values—Automatic (the service starts automatically), Manual (the service starts manually), Disabled (the service is disabled).
The names of the services to be changed are specified as the value of the -Name parameter (the names may contain wildcards). For example, we will change the startup mode of the LarnanServer server service. Let’s look at all the features of this service:
PS С:\> Get-Service LanmanServer | Format-List *
As you can see, this service is now started automatically (the value of the StartType property is Automatic). Let’s use the Set-Service cmdlet to change the startup mode of the LamnanServer service from automatic to manual:
PS С:\> Set-Service -Name LanmanServer -StartupType Manual
Let’s take another look at the LarnanServer service properties to verify the changes:
PS С:\Users\andrv> Get-Service LanmanServer | Format-List Name, StartType Name : LanmanServer StartType : Manual
As you can see, the value of the StartType property has been successfully changed.
Note that the service description is not a property of System Objects. ServiceProcess . ServiceContr011er is returned by the Get-Service cmdlet. In other words, the Get-Service cmdlet does not allow you to see the description of a specific service.
You can solve this problem using WMl-uacca Win32 Service, which has the Description property. Let’s see what the value of this property is for the LanmanServer service:
PS С:\> Get-WtaiObject win32_service -Filter "name = 'LanmanServer'" | Format-List Name, Description
In Chapter 11, we looked at an example of using the methods provided by external COM objects to solve the problem of creating a shortcut on the desktop. This standard for software components, the Component 0bject Model (COM), became the basis for the 0bject Linking and Embedding (OLE) technology, which was originally used in Windows to communicate between programs.
Initially, OLE was used to create composite documents, and then to solve the more general problem of providing applications with their own functions (services) to each other and using these functions correctly. The technology that allows one application (automation component) to call the functions of another application (automation server) is called OLE Automation.
Since the mid-1990s, the term OLE has been replaced by the new term ActiveX, which originally meant (objects) based on COM technology. Before the advent of the .NET platform, ActiveX was a key technology in Microsoft products.
One of the most common and frequently used automation servers in Windows is the Microsoft 0f6ce application package. We’ll look at examples of how you can output information from PowerShell to two of the most common PowerShell applications: Microsoft Word and Microsoft Excel. However, first of all, let’s say a few words about the object models presented by these programs.
In order to use the capabilities of Word and Excel from PowerShell, you need to know which objects are exposed for external use by these automation servers and how these objects relate to each other.
Although the object models of various Microsoft 0ffce applications are quite large, they are similar to each other, and for practical purposes it is enough to understand how to work with a few key objects. Instead of going into detail about the properties and methods of Word and Excel objects, we will only briefly mention which objects will be used in the following example scenarios.
At the very top level of the Word object model is the App1ication object, which directly represents the Word application itself and contains (as properties) all other objects. Thus, the App1ication object is used to access any other Word object.
The Docuents family is a property of the App1ication object and contains a set of Docuents, each of which corresponds to a document opened in Word. To create new documents, we will need the Docunents class in the scripts. The Document object contains as its properties a family of different document objects: Symbols, Words, Sentences, Paragraphs, Bookmarks, etc.
The Se1ection object allows you to work with a selected fragment of text (this fragment can be empty). Thus, we can say that the Se1ection object opens the path to the document, because it provides access to the selected part of the document. In particular, the Se1ection object has a TypeText method that can be used to insert text into the document. Using the properties of this object (which, in turn, can be objects with their own properties), you can control selection parameters, such as setting the desired font size and typeface, centering paragraphs, and so on.
The object model of Excel is built according to the same principle as the object model of Word. The main object that contains all the others is App1ication. Recall that individual files in Excel are called workbooks. The “Books” family in Excel is analogous to the “Documents” family in Word and contains a set of “Book” objects (similar to the “Documentation” object in Word), each of which corresponds to a book opened in Excel. A new workbook is created using the Add() method of the Workbooks object.
Excel uses the Ce11s property of the App1ication object to access the cells of the active worksheet. To get or change the value of an individual cell, the Ce11s construct is used. Pet (row, co1itp) . Va1ue, where row and co1spp are the numbers of rows and columns, respectively, at the intersection of which this cell is located.
In Excel, as in Word, there is an object. Se1ection, which allows you to work with a selected fragment of a spreadsheet. The easiest way to isolate a range of cells on the active sheet is to use the Se1ect( ) method of the Range object. For example, the expression Range (“A1 : C1”) . Se1ect ( ) allows you to select three adjacent cells: A1, B1 and C1.
In order to understand which Word or Excel object should be used to solve a particular task, it is often easiest to perform the necessary manipulations manually in the corresponding application, having previously turned on the macro recording mode. As a result, we will receive the text of the macro in VBA (Visual Basic for Applications), from which it will be clear which methods and with which parameters should be called, and which values should be assigned to the properties of the object.
Let’s learn how to use PowerShell to control Microsoft Word: launch the program from the shell and type a line of text in the Word window. It is easy to do. First, we create an instance of the main object of the Microsoft Word automation server, which has the ID of the Word program. App1ication, and store a reference to this object in the $word variable:
PS С:\> $word = New-Object -ComObject Word.Application
Using the Add method of the Docunents collection, create a new document and store a reference to it in the $doc variable:
PS С:\> $doc = $word.Documents .Add()
Make the new document window visible. To do this, you need to write $true in the Visib1e property of the $word object:
PS С:\> $word.Visible = $true
In the $se 1 variable, add a reference to the Se1ection object, which can be used to set the font type and size, paragraph alignment type, and tayuke for printing lines of text in the document:
PS С:\> $sel = $word.Selection Встановимо розмір шрифту: PS С:\> $sel.Font.Size = 14 Встановимо жирний шрифт: PS С:\> $sei.Font.Bold = $true Зрештою, друкуємо рядок тексту: PS С:\> $sel.TypeText("Привіт з PowerShell!")
Let’s create a new MicrosoR Excel workbook with PowerShell and output the title and one phonebook entry to it. As in Microsoft Word, first we create an instance of the main object Exe1. App1ication and store a reference to this instance in the $XL variable:
PS С:\> $XL = New-Object -ComObject Excel.Application
As a result, Microsoft Excel is launched. To make the application window visible, set the Visib1e property value to $true:
PS С:\> $XL.Visible = $true
You can create a new book using the “Add” method of the “Books” collection; When this method is executed, a lot of unnecessary technical information is displayed on the screen, which we will redirect to the empty device $null:
PS С:\> $XL.WorkBooks.Add() > $null
Now you can set the required width of the column (property C01umnWidth) and display the header text:
PS С:\> #Устанавливаем нужную ширину колонок PS С:\> $XL.Columns.Item(1) .ColumnWidth = 40 PS C: \ > $XL. Columns. Itern (2) . ColumnWidth = 40 PS C:\> $XL.Columns.Item(3) .ColumnWidth = 40 PS C:\> #Печатаем в ячейках текст PS С:\> $XL.Cells.Item(1,1) .Уа1ие="Фамилия" PS C:\> $XL.Cells.Item(1,2).Уа1ие="Имя" PS C:\> $XL.Cells.Item(1,3).Value="Телефон"
Use the Select ( ) method to select the three cells with the entered title and set them to bold:
PS С:\> #Выделяем три ячейки PS С:\> $XL. Range ("Al: С1"). Select () > $null PS С:\> #Устанавливаем полужирный шрифт для выделенного диапазона PS С:\> $XL.Selection.Font.Bold = $true
In the second line of the work book, we display the subscriber’s data:
PS С:\> $XL.Cells.Item(2,1).Value="Иванов" PS C:\> $XL.Cells.Item(2,2) .Уа1ие="Иван" PS C:\> $XL.Cells.Item(2,3) .Value="555555"
Get-Process, Start-Process, and Stop-Process cmdlets are used to manage processes on the local machine. Processes on a remote machine can be accessed using WMI using the win32_Process class.
Cmdlets Get-Service, Start-Service, Stop-Service are designed to work with services on the local computer.
Using the New-oject cmdlet with the -Comobject parameter, you can access services provided by automation servers.