Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 34 ยท Real-World Use

Processes, Services and the System

Manage processes, services, event logs and scheduled tasks with PowerShell: Get-Process, Stop-Process, Get-Service, Get-WinEvent and Get-CimInstance explained.

PowerShell began as a tool for Windows administrators, and this is where it earns its keep: asking a machine what is running, stopping what should not be, restarting services, reading the event log and scheduling work. The cmdlets return objects, so the questions you ask are the same ones you already know how to write with Where-Object, Select-Object and Sort-Object: "which five processes use the most memory?", "which automatic services are stopped?".

The commands in this lesson act on the real machine, so they are shown read-only here, and the site cannot run them. The runnable examples use sample data and small JavaScript models. They are stand-ins: they reproduce the shape of the output and the main rules, not the operating system. Several commands need an elevated (administrator) session, and the service, event log, CIM and scheduled-task cmdlets are Windows-only. Get-Process works on Windows, Linux and macOS.

Four things to manage

Processes Programs that are running now.
Services Background programs with a start type.
Event logs What the system recorded.
Scheduled tasks Work that starts by itself.

Same pattern for all four, Get then Stop or Set.

1 / 2

Processes

Get-Process returns one object per running process. The properties you will use most are Name, Id, CPU (total processor time in seconds, not a percentage), WorkingSet64 (memory in bytes) and StartTime (which may be unavailable for processes of other users unless you are elevated).

POWERSHELL
Get-Process                                   # everything
Get-Process -Name chrome, code                # by name, wildcards allowed
Get-Process |
  Sort-Object WorkingSet64 -Descending |
  Select-Object -First 5 Name, Id, @{ n = 'MB'; e = { [math]::Round($_.WorkingSet64 / 1MB) } }

Get-Process | Group-Object Name | Sort-Object Count -Descending | Select-Object -First 3

To end a process, use Stop-Process, by name or id or through the pipeline. Always preview first:

POWERSHELL
Stop-Process -Name notepad -WhatIf            # shows what would be stopped
Get-Process notepad | Stop-Process            # pipeline form
Stop-Process -Id 4812 -Force
Start-Process notepad -PassThru               # start one and get its object
Wait-Process -Id 4812 -Timeout 30

Stop-Process ends the process abruptly, with no chance to save work, so prefer closing programs politely ($p.CloseMainWindow()) when users might have unsaved data. Name matching is by process name without .exe, so use chrome, not chrome.exe.

The model below works on sample data shaped like Get-Process output. It sorts, groups and previews a stop with -WhatIf.

JS Sample processes: sort, group and -WhatIf

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The -WhatIf line imitates PowerShell's wording; the exact text on a real system differs a little. Note that chrome appears three times: a browser runs many processes, which is why grouping by name gives a more honest memory total than looking at single rows.

Services

A service is a program managed by the operating system that runs in the background, often starting at boot, without a window. Get-Service shows Name, DisplayName, Status (Running, Stopped, Paused) and StartType (Automatic, Manual, Disabled).

POWERSHELL
Get-Service
Get-Service -Name Spooler, W32Time
Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' }

Restart-Service -Name Spooler                 # needs an elevated session
Stop-Service -Name Spooler -WhatIf
Set-Service -Name Spooler -StartupType Manual
Get-Service -Name LanmanServer -DependentServices

Services depend on each other. Stopping a service that others need fails with an error unless you add -Force, which stops the dependent services too. That is why you check -DependentServices before a forced stop on a production machine. Changing a start type or stopping a system service can break the machine, so be deliberate.

The model below captures start types, dependency rules and the effect of -Force.

JS A service model with dependencies and -Force

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The wording of the errors paraphrases the real ones. What carries over to a real machine is the logic: a stop is refused while running services depend on the target, -Force takes the dependents down with it, and a starting service pulls in what it requires first.

Event logs

Windows records events in logs such as System, Application and Security. Get-WinEvent reads them and is the modern cmdlet (the older Get-EventLog exists only in Windows PowerShell 5.1). Always filter on the server side with -FilterHashtable, which is much faster than fetching everything and piping to Where-Object:

POWERSHELL
Get-WinEvent -LogName System -MaxEvents 10

Get-WinEvent -FilterHashtable @{
    LogName   = 'System'
    Level     = 2                          # 1 critical, 2 error, 3 warning, 4 information
    StartTime = (Get-Date).AddDays(-1)
} | Select-Object TimeCreated, Id, ProviderName, Message -First 20

Reading the Security log needs elevation. On Linux and macOS this cmdlet does not exist; use the platform's own log tools, and call them from PowerShell as native commands.

CIM instead of WMI

Windows exposes hardware and system data through WMI classes. Old scripts use Get-WmiObject, which exists only in Windows PowerShell 5.1 and was removed from PowerShell 7. The replacement is Get-CimInstance:

POWERSHELL
Get-CimInstance -ClassName Win32_OperatingSystem |
  Select-Object Caption, Version, LastBootUpTime

Get-CimInstance Win32_LogicalDisk -Filter "DriveType = 3" |
  Select-Object DeviceID,
    @{ n = 'SizeGB'; e = { [math]::Round($_.Size / 1GB, 1) } },
    @{ n = 'FreeGB'; e = { [math]::Round($_.FreeSpace / 1GB, 1) } }

$session = New-CimSession -ComputerName server01          # query a remote machine
Get-CimInstance -CimSession $session -ClassName Win32_BIOS

Use -Filter (WQL syntax) to let the provider do the filtering. CIM sessions are the basis for querying remote computers; the next lesson covers remoting in detail in Remoting, Jobs and Parallelism.

Scheduled tasks

The ScheduledTasks module (Windows) creates and manages Task Scheduler jobs:

POWERSHELL
$action  = New-ScheduledTaskAction -Execute 'pwsh.exe' -Argument '-NoProfile -File C:\Scripts\cleanup.ps1'
$trigger = New-ScheduledTaskTrigger -Daily -At 3am
Register-ScheduledTask -TaskName 'NightlyCleanup' -Action $action -Trigger $trigger

Get-ScheduledTask -TaskName 'NightlyCleanup' | Get-ScheduledTaskInfo
Start-ScheduledTask -TaskName 'NightlyCleanup'
Unregister-ScheduledTask -TaskName 'NightlyCleanup' -Confirm:$false

Registering a task normally needs an elevated session. Give tasks a script file and full paths: they do not run in your current folder, so relative paths and your profile cannot be assumed. The -NoProfile argument keeps the run predictable.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the CPU property of a Get-Process object contain?

    CPU is accumulated processor time in seconds. To get a percentage you must sample twice and compute the difference yourself.
  2. 2. Why use Stop-Process -Name notepad -WhatIf first?

    -WhatIf previews the action. It is a safety habit for any command that stops, removes or changes things.
  3. 3. Which cmdlet replaces Get-WmiObject in PowerShell 7?

    Get-WmiObject was removed in PowerShell 7. Get-CimInstance queries the same classes, and it also supports -CimSession for remote machines.
  4. 4. Stop-Service fails because other services depend on the target. What does -Force do?

    -Force stops dependent services too. Check Get-Service -DependentServices first, because the effect can be wider than you expect.
  5. 5. Why prefer Get-WinEvent -FilterHashtable over piping Get-WinEvent to Where-Object?

    With -FilterHashtable the filtering happens in the event log service, so only matching events are sent to PowerShell.

Summary

  • Get-Process and Stop-Process manage processes; CPU is seconds of processor time and WorkingSet64 is memory in bytes. Preview with -WhatIf.
  • Get-Service, Start-Service, Stop-Service, Restart-Service and Set-Service manage services; -Force also stops dependent services.
  • Get-WinEvent -FilterHashtable reads event logs efficiently on Windows; Get-EventLog exists only in Windows PowerShell 5.1.
  • Get-CimInstance replaces Get-WmiObject, which was removed in PowerShell 7.
  • The ScheduledTasks cmdlets register jobs that start by themselves; use scripts, full paths and -NoProfile.
  • Service, event log, CIM and task cmdlets are Windows-only; many need an elevated session.

Next, run work on other machines and in parallel with Remoting, Jobs and Parallelism.