E-NO
PowerShell commands 7 Min Read

PowerShell Basic Commands with Practical Examples: A Hands-On Guide for Daily Operations

calendar_today Published: 2026-10-22
update Last Updated: 2026-10-22
analytics SEO Efficiency: 100%
Technical guide illustration for PowerShell Basic Commands with Practical Examples: A Hands-On Guide for Daily Operations.

Intro

PowerShell basic commands with practical examples help operators move from an observed problem to a verified result. Start by identifying the installed version, deployment topology, prerequisites, and the exact component being inspected.

This article focuses on PowerShell commands for developers, DevOps consultants, and technical startup teams. It connects essential commands, examples, cheat-sheet references, and operational procedures to expected output, failure signals, and recovery decisions that match real-world scenarios.

The goal is operational safety: observe before changing, limit the blast radius, use placeholders instead of secrets, verify the result, and document how to recover if the expected state is not reached.

Version and Environment Inventory

Before running any command, know what you are working with. Checking the PowerShell version, edition, and host environment prevents compatibility surprises. Use the following read-only commands:

# PowerShell version and edition
$PSVersionTable.PSVersion
$PSVersionTable.PSEdition
$PSVersionTable.OS

Expected output on a typical Windows 10/11 or Server 2019/2022 system:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      19041  1320
Desktop
Microsoft Windows 10.0.19044

On PowerShell Core 7.x, you will see Core instead of Desktop and a cross-platform OS description. Always record the version before scripting; many cmdlets and parameters differ between Windows PowerShell 5.1 and PowerShell 7+.

If you manage multiple machines, gather the same information remotely with Invoke-Command:

Invoke-Command -ComputerName SERVER01 -ScriptBlock { $PSVersionTable.PSVersion }

Failure signal: if the remote command fails with "WinRM cannot complete the operation" or "Access is denied", verify that WinRM is enabled (Enable-PSRemoting -Force) and that your account has administrative rights on the target.

To check the execution policy, which controls whether scripts can run, use:

Get-ExecutionPolicy -List

A typical safe output shows Restricted (default) or RemoteSigned (recommended for local scripts). To allow locally created scripts while blocking unsigned remote scripts, set:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Blast radius: this affects only the current user's script execution policy, not the whole machine. Verification: run Get-ExecutionPolicy again and confirm it returns RemoteSigned.

Common pitfall: confusing $PSVersionTable.PSVersion with the product version shown in the Windows Features dialog. PowerShell 5.1 is built into Windows, while PowerShell 7+ is installed separately and may be referenced as pwsh instead of powershell. Always confirm which executable you are using with (Get-Process -Id $PID).ProcessName.

Safe Configuration Path

Changing configuration should follow a predictable path: observe current state, apply the smallest change, verify, and have a rollback plan.

Example: Setting a System Environment Variable

First, observe the current value:

[Environment]::GetEnvironmentVariable("MY_APP_HOME", "Machine")

If the variable does not exist, the output is empty. To set it for all users (requires admin rights):

[Environment]::SetEnvironmentVariable("MY_APP_HOME", "C:\Apps\MyApplication", "Machine")

To use the new value in the current session without logging off, also update the process scope:

$env:MY_APP_HOME = "C:\Apps\MyApplication"

Blast radius: this changes the environment for all users on the machine, which may affect any service or application that reads this variable. Verify with:

[Environment]::GetEnvironmentVariable("MY_APP_HOME", "Machine")

Expected output: C:\Apps\MyApplication.

Rollback: if the change causes issues, delete the variable with:

[Environment]::SetEnvironmentVariable("MY_APP_HOME", $null, "Machine")

Common pitfall: attempting to set a machine-scoped variable without an elevated prompt. The command appears to succeed but does not persist, or throws "Requested registry access is not allowed." Always run PowerShell as administrator for machine-scoped changes.

Example: Modifying a Registry Key Safely

Changing the registry requires care. First, back up the key:

$backupPath = "C:\RegBackups\MyKey.reg"
reg export HKLM\Software\MyApp $backupPath

Verify the backup exists:

Test-Path $backupPath

If it returns True, you can proceed. To change a value:

Set-ItemProperty -Path "HKLM:\Software\MyApp" -Name "LogLevel" -Value "Debug"

Verify:

Get-ItemProperty -Path "HKLM:\Software\MyApp" -Name "LogLevel"

Expected output:

LogLevel : Debug
PSPath   : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software\MyApp
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\Software
PSChildName  : MyApp
PSDrive      : HKLM
PSProvider   : Microsoft.PowerShell.Core\Registry

Rollback: if something breaks, restore the backup:

reg import $backupPath

Common pitfall: using Set-ItemProperty on a registry key that does not exist. The command throws "Property LogLevel does not exist at path..." unless the key and property are already present. To create a new property, use New-ItemProperty first.

Verification and Diagnostics

After any change, verify the system state. Use built-in cmdlets to retrieve information and compare it with expected values.

Service Health Check

Suppose you restarted a service and need to confirm it is running and accepting requests. Use:

Get-Service -Name "Spooler" | Select-Object Name, Status, StartType

Expected output:

Name    Status StartType
----    ------ ---------
Spooler Running Automatic

For deeper diagnostics, check recent events from the service:

Get-WinEvent -LogName System -MaxEvents 20 | Where-Object { $_.ProviderName -like "*Spooler*" -or $_.Message -like "*Spooler*" } | Select-Object TimeCreated, Id, LevelDisplayName, Message

If the service fails to start, look for error events like Event ID 7034 (service terminated unexpectedly) or 7000 (service failed to start).

Common pitfall: assuming a service is healthy because its status is "Running." A service can be running but hung or not serving requests. Always test functionality, for example, by sending a test print job (for spooler) or calling an API endpoint.

Network Connectivity Test

Use Test-NetConnection to verify connectivity and port availability:

Test-NetConnection -ComputerName "db.example.com" -Port 1433

Expected output on success:

ComputerName     : db.example.com
RemoteAddress    : 10.0.0.15
RemotePort       : 1433
InterfaceAlias   : Ethernet
SourceAddress    : 10.0.0.100
TcpTestSucceeded : True

If TcpTestSucceeded is False, check DNS resolution, firewall rules, and whether the service is listening:

Resolve-DnsName "db.example.com"
Get-NetFirewallRule -DisplayName "*SQL*" | Select-Object DisplayName, Enabled, Action

Common pitfall: using Test-Connection (ICMP ping) to test a port. Ping only checks host availability, not a specific service. Many firewalls block ICMP even when the target port is open.

Failure Modes and Recovery

Every operation can fail. Having a documented recovery path reduces downtime and stress.

Disk Space Exhaustion

A common failure is a full disk. Detect with:

Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{Name="UsedGB";Expression={[math]::Round($_.Used/1GB,2)}}, @{Name="FreeGB";Expression={[math]::Round($_.Free/1GB,2)}}

Output for a nearly full C: drive:

Name UsedGB FreeGB
---- ------ ------
C    236.10  10.50
D    500.00 250.00

If free space drops below 10%, investigate large files:

Get-ChildItem -Path C:\ -Recurse -File -ErrorAction SilentlyContinue | Sort-Object Length -Descending | Select-Object -First 10 FullName, Length

Recovery: delete or archive unnecessary files, clear temp folders, and expand the volume if possible.

Common pitfall: ignoring -ErrorAction SilentlyContinue when scanning the whole drive; without it, access-denied errors clutter the output. Also, avoid deleting files without confirming they are not in use; use Get-Process | Where-Object { $_.Path -like 'C:\LargeFile*' } to see if a process holds the file.

Locked File or Process

Sometimes a file cannot be deleted because a process has it locked. Identify the process:

Get-Process | Where-Object { $_.Modules.FileName -contains "C:\Path\To\File.txt" }

If that is slow, use Sysinternals handle.exe (if installed) for a faster lookup:

handle.exe "C:\Path\To\File.txt"

Recovery: stop the process gracefully with Stop-Process -Name ProcessName -Force if it is safe, then retry the deletion.

Common pitfall: force-killing a critical system process. Always verify the process name and its purpose before stopping. In a production server, schedule a maintenance window or coordinate with other teams.

Operations Checklist

Use this checklist before and after any PowerShell operation. Each item includes the responsible role and review frequency to maintain accountability.

StepTaskCommand/CheckOwnerReview Frequency
1Record PowerShell version$PSVersionTable.PSVersionDevOps EngineerMonthly or before major changes
2Backup registry keys or config filesreg export HKLM\Software\MyApp C:\backup\myapp.regSystem AdministratorBefore each change
3Test connectivity to critical endpointsTest-NetConnection -ComputerName db.example.com -Port 1433Network EngineerWeekly
4Check disk spaceGet-PSDrive CSystem AdministratorDaily via scheduled script
5Verify service status after changesGet-Service -Name SpoolerApplication OwnerAfter each change or deployment
6Review event logs for errorsGet-WinEvent -LogName System -MaxEvents 50Security AnalystWeekly
7Confirm execution policyGet-ExecutionPolicyDevOps EngineerQuarterly
8Test rollback procedureRun backup/restore on a staging environmentRelease ManagerBefore each production release

Common pitfall: treating the checklist as a one-time activity. Operations environments evolve; revisit and update the checklist monthly or whenever a failure reveals a gap.

Common Pitfalls and How to Avoid Them

1. Running Commands Without Understanding Them

Copy-pasting scripts from the internet can introduce security risks or unintended changes. Always read the command, replace placeholders, and test on a non-production system first. Use -WhatIf and -Confirm parameters where available:

Remove-Item C:\Temp\* -WhatIf

This shows what would happen without actually deleting files.

2. Using Credentials in Plain Text

Hardcoding passwords in scripts is a major security hole. Use secure strings and credential objects:

$cred = Get-Credential
Invoke-Command -ComputerName SERVER01 -Credential $cred -ScriptBlock { Get-Service }

Alternatively, use Windows Credential Manager or Azure Key Vault for automated scripts.

3. Ignoring Error Handling

A script that fails silently can leave systems in an inconsistent state. Always set $ErrorActionPreference = "Stop" in critical scripts and use try/catch blocks:

try {
    Get-Item C:\ImportantFile.txt -ErrorAction Stop
} catch {
    Write-Host "File not found: $($_.Exception.Message)" -ForegroundColor Red
    # trigger alert or recovery
}

4. Not Testing Rollback

Having a backup is not enough; you must know how to restore it. Regularly test rollback procedures in a staging environment. Simulate a failed deployment and time how long it takes to recover.

5. Using Old Cmdlets in New PowerShell Versions

Some cmdlets have been replaced or renamed. For example, Get-WMIObject is deprecated in PowerShell 6+; use Get-CimInstance instead. Always check compatibility for your target PowerShell version.

Conclusion

PowerShell basic commands with practical examples become valuable only when each recommendation is version-scoped, observable, and reversible where the technology permits. Copying a command without checking prerequisites and expected output is not an operations procedure.

As a next step, choose one low-risk verification technique from this guide, record the current state, run the documented check, compare the result with the expected signal, and review dependencies such as Windows automation, Docker, and GitLab CI/CD pipelines.

A reliable technical workflow makes failure visible, protects sensitive values, limits changes to the intended resource, and defines recovery verification before an incident forces the decision.

Related Research

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL