Environment Variables, Processes, and Services
Prerequisites: The pipeline
Environment variables
$env:APP_MODE = 'staging'
"Mode: $env:APP_MODE"
$null -eq $env:MISSING
Test-Path Env:APP_MODE
Remove-Item Env:APP_MODE
Test-Path Env:APP_MODE
Mode: staging
True
True
False
$env:NAMEreads and sets environment variables for the current session and the programs it starts.- The
Env:drive lets you useGet-ChildItem Env:,Test-Path, andRemove-Itemon them. - To set one permanently on Windows:
[Environment]::SetEnvironmentVariable('NAME', 'value', 'User').
Processes
# illustrative
Get-Process | Sort-Object WorkingSet -Descending | Select-Object -First 5 Name, Id,
@{ Name = 'MemoryMB'; Expression = { [math]::Round($_.WorkingSet / 1MB) } }
Start-Process notepad
Get-Process notepad | Stop-Process
Name Id MemoryMB
---- -- --------
chrome 8124 612
Code 11220 498
Teams 6632 401
pwsh 9310 142
explorer 5204 118
Run an external program and wait for it, capturing its exit code:
# illustrative
$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList '/i app.msi /quiet' -Wait -PassThru
$p.ExitCode
Console programs can also be called directly (git status); their exit
code is in $LASTEXITCODE.
Services (Windows)
# illustrative
Get-Service -Name Spooler
Get-Service | Where-Object { $_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic' }
Restart-Service -Name Spooler -WhatIf
Set-Service -Name Spooler -StartupType Manual
Changing services requires an elevated (Run as administrator)
session. On Linux, manage services with systemctl, called from
PowerShell like any other program.
The registry (Windows)
The registry is exposed as drives, so the file cmdlets work on it:
# illustrative
Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' |
Select-Object ProductName, DisplayVersion
New-ItemProperty -Path 'HKCU:\Software\MyApp' -Name Theme -Value dark