Um momento
0x140Lesson 21 of 24

Looking after computers

Inspect and control processes, services, disks, the network and files - the everyday jobs PowerShell was built for.

28 min 6-question quiz 2 code exercises
By the end of this lesson you can
  • Find, start and stop processes, and manage Windows services
  • Query system information with CIM, read event logs and test network connections
  • Measure disk usage with size suffixes, spot identical files with Get-FileHash, and zip folders

PowerShell was born to look after computers - Jeffrey Snover’s original pitch was a shell for Windows administrators. The sanctuary’s server room (two humming boxes behind the hay loft) needs a keeper too. Everything in this lesson is just cmdlets returning objects, so all your pipeline skills apply.

Start with processes - running programs. Get-Process lists them as objects with CPU, WorkingSet (memory in bytes), Id and StartTime properties.

processes.ps1
1# The five hungriest programs, by memory
2Get-Process | Sort-Object WorkingSet -Descending |
3  Select-Object -First 5 Name, Id, @{ Name = 'MB'; Expression = { [math]::Round($_.WorkingSet / 1MB) } }
4
5# Your own PowerShell session: $PID is its process id
6Get-Process -Id $PID
7
8# Start a program and wait for it to finish
9$job = Start-Process -FilePath 'pwsh' -ArgumentList '-NoProfile', '-Command', 'Start-Sleep 2' -PassThru -Wait
10"exit code: $($job.ExitCode)"
11
12# Stop a runaway program - preview first!
13Get-Process -Name 'notepad' -ErrorAction SilentlyContinue | Stop-Process -WhatIf

Size suffixes make byte counts readable: 1KB is 1024, 1MB is 1024 × 1024, and GB, TB and PB follow. Divide by them to convert, and round for display.

sizes.ps1
11KB
21MB
35GB / 1GB
4[math]::Round(123456789 / 1MB, 1)
5$folder = [pscustomobject]@{ Name = 'photos'; Bytes = 6656 }
6"$($folder.Name): $([math]::Round($folder.Bytes / 1KB, 1)) KB"
Output
1024
1048576
5
117.7
photos: 6.5 KB

Services, system information and logs (Windows)

A service is a program that runs in the background without a window - a web server, a print spooler, the sanctuary’s egg-temperature monitor. On Windows, Get-Service, Start-Service, Stop-Service and Restart-Service manage them (changing them needs an administrator prompt).

CIM (the Common Information Model) is Windows’ giant catalog of facts about the machine: operating system, disks, memory, BIOS, installed hardware. Get-CimInstance -ClassName <class> queries it - locally or, with -ComputerName, on other machines.

Event logs record what Windows and its programs did. Get-WinEvent -FilterHashtable filters at the source, which is far faster than piping every event to Where-Object.

windows-admin.ps1
1# Which automatic services aren't running?
2Get-Service | Where-Object { $_.StartType -eq 'Automatic' -and $_.Status -ne 'Running' }
3Restart-Service -Name 'Spooler' -WhatIf
4
5# How full is each disk?
6Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType = 3' |
7  Select-Object DeviceID, @{ Name = 'FreeGB'; Expression = { [math]::Round($_.FreeSpace / 1GB, 1) } }
8
9# When did this machine last start?
10(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime
11
12# Errors from the last 24 hours
13Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 2; StartTime = (Get-Date).AddDays(-1) } -MaxEvents 20

Network checks

network.ps1
1# Is the server up? (ping)
2Test-Connection -TargetName 'emberfall-nas' -Count 2
3
4# Is the web server listening on port 443? (PowerShell 7)
5Test-Connection -TargetName 'emberfall.example' -TcpPort 443
6
7# The Windows classic, with more detail
8Test-NetConnection -ComputerName 'emberfall.example' -Port 443
9
10# Which name does the DNS server give back? (Windows)
11Resolve-DnsName 'emberfall.example'

Files: fingerprints and archives

Get-FileHash computes a file’s hash - a fingerprint made from its contents. Identical contents give identical hashes whatever the file is called, so hashing finds duplicates, and comparing against a published hash proves a download wasn’t corrupted or tampered with. The default algorithm is SHA256.

Compress-Archive and Expand-Archive zip and unzip, so a nightly backup can be one line.

hashes.ps1
1$root = Join-Path ([IO.Path]::GetTempPath()) (New-Guid)
2New-Item -ItemType Directory -Path $root | Out-Null
3Set-Content -Path (Join-Path $root 'ember.egg') -Value 'speckled red' -NoNewline
4Set-Content -Path (Join-Path $root 'copy-of-ember.egg') -Value 'speckled red' -NoNewline
5Set-Content -Path (Join-Path $root 'glim.egg') -Value 'glowing blue' -NoNewline
6Get-ChildItem $root | Get-FileHash | Group-Object Hash |
7  Where-Object Count -gt 1 |
8  ForEach-Object { 'twins: ' + (($_.Group.Path | Split-Path -Leaf | Sort-Object) -join ', ') }
9Remove-Item $root -Recurse
Output
twins: copy-of-ember.egg, ember.egg
nightly-backup.ps1
$stamp = Get-Date -Format 'yyyy-MM-dd'
Compress-Archive -Path 'D:\Sanctuary\Records\*' -DestinationPath "E:\Backups\records-$stamp.zip"
Expand-Archive -Path "E:\Backups\records-$stamp.zip" -DestinationPath 'D:\Restore' -WhatIf

Try it

Works everywhere, or Windows only?

Your script has to run on the Windows server and the Linux box. Sort the commands.

0 of 8 sortedScore 0/0
  • “Get-Process”

  • “Get-Service”

  • “Get-FileHash”

  • “Get-CimInstance Win32_OperatingSystem”

  • “Compress-Archive”

  • “Get-WinEvent”

  • “Test-Connection -TcpPort 443”

  • “Get-ItemProperty HKLM:\Software\Emberfall”

Key takeaways

  • Get-Process, Start-Process -Wait -PassThru and Stop-Process -WhatIf manage programs; $PID is your own.

  • On Windows, *-Service, Get-CimInstance and Get-WinEvent -FilterHashtable cover services, system facts and logs.

  • Test-Connection (with -TcpPort in PowerShell 7) checks the network.

  • Divide by 1KB/1MB/1GB and round to show sizes; Get-FileHash fingerprints files; Compress-Archive zips them.

Lesson quiz

6 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write PowerShell scripts

Write a script in the editor and run it for real against sample input, which is piped into your script as $input. Scripts run on PowerShell 6.2 through Try It Online (tio.run), a free public service, so these exercises avoid PowerShell 7-only syntax; your script and test input are sent there.

Exercise 1

Twin eggs

+25 XP

Somebody saved the egg photos twice under different names. Each input line is a file name and its contents, like glim.egg glowing-blue. Create the files in a new temporary folder (write the contents with -NoNewline), then use Get-FileHash to find files with identical contents.

For each set of duplicates print same egg: <names> (names sorted, comma-separated; sets in the order of their first name). If there are none, print no duplicates. Finish with distinct eggs: <n>.

  • A copy and a backup
  • All different
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Exercise 2

The storage detective

+25 XP

The server is filling up. Each input line is folder/file sizeInBytes, like photos/ember.png 4096. Create the folders and files in a new temporary folder ([IO.File]::WriteAllBytes($path, [byte[]]::new($size)) makes a file of exactly that size).

Then measure each folder with Get-ChildItem and Measure-Object and print the biggest first: photos: 6.5 KB (2 files) - kilobytes rounded to 1 decimal, and file when there’s just one. Finish with total: <KB> KB.

  • Photos and logs
  • Maps and notes
script.ps1
Loading editor…

Lessons teach PowerShell 7; your script runs on PowerShell 6.2 via Try It Online (tio.run), a free public service, so stick to syntax that works there. Test input is piped into your script as $input. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: