70+ Essential Powershell Commands

File and Directory Commands

  1. Get-ChildItem (Windows: dir) Lists files/directories.

# Basic: List files with details
Get-ChildItem -Path .
# Advanced: List .txt files recursively
Get-ChildItem -Path . -Recurse -Include *.txt | Format-Table Name, Length
  1. Set-Location (Windows: cd) Changes directory.

# Basic: Navigate to a folder
Set-Location -Path C:\Users
# Advanced: Switch to path with spaces
Set-Location -Path "C:\Program Files (x86)"
  1. New-Item -ItemType Directory (Windows: mkdir/md) Creates a directory.

# Basic: Create a single folder
New-Item -Path Data -ItemType Directory
# Advanced: Create nested folders
New-Item -Path Parent\Child\Grandchild -ItemType Directory -Force
  1. Remove-Item -Directory (Windows: rmdir/rd) Deletes a directory.

# Basic: Remove empty folder
Remove-Item -Path Data -Directory
# Advanced: Remove non-empty folder
Remove-Item -Path Data -Recurse -Force
  1. Remove-Item (Windows: del) Deletes files.

# Basic: Delete a file
Remove-Item -Path temp.txt
# Advanced: Delete all .log files silently
Remove-Item -Path *.log -Force
  1. Copy-Item (Windows: copy) Copies files.

# Basic: Copy a file
Copy-Item -Path file.txt -Destination D:\Backup
# Advanced: Copy multiple files with overwrite
Copy-Item -Path *.txt -Destination D:\Backup -Force
  1. Copy-Item -Recurse (Windows: xcopy) Copies directories recursively.

# Basic: Copy a directory
Copy-Item -Path Data -Destination D:\Backup
# Advanced: Copy with hidden files
Copy-Item -Path Data -Destination D:\Backup -Recurse -Force
  1. Move-Item (Windows: move) Moves/renames files.

# Basic: Move a file
Move-Item -Path file.txt -Destination D:\Archive
# Advanced: Rename multiple files
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '.txt','.bak' }
  1. Set-ItemProperty -Name Attributes (Windows: attrib) Changes file attributes.

# Basic: Hide a file
Set-ItemProperty -Path secret.txt -Name Attributes -Value Hidden
# Advanced: Make folder read-only and hidden
Set-ItemProperty -Path Data -Name Attributes -Value ([System.IO.FileAttributes]::ReadOnly + [System.IO.FileAttributes]::Hidden)
  1. Rename-Item (Windows: ren) Renames files/directories.

# Basic: Rename a file
Rename-Item -Path old.txt -NewName new.txt
# Advanced: Bulk rename files
Get-ChildItem *2023*.txt | Rename-Item -NewName { $_.Name -replace '2023','2024' }

System Information Commands

  1. Get-ComputerInfo (Windows: systeminfo) Shows system information.

# Basic: Display OS name
Get-ComputerInfo | Select-Object WindowsProductName
# Advanced: Export system info to file
Get-ComputerInfo | Export-Csv -Path sysinfo.csv
  1. $env:COMPUTERNAME (Windows: hostname) Shows computer name.

# Basic: Get hostname
$env:COMPUTERNAME
# Advanced: Log hostname
$env:COMPUTERNAME | Out-File device.txt
  1. Get-CimInstance Win32_OperatingSystem (Windows: ver) Shows OS version.

# Basic: Check version
Get-CimInstance Win32_OperatingSystem | Select-Object Version
# Advanced: Filter specific version
(Get-CimInstance Win32_OperatingSystem).Version -match "10.0"
  1. Get-ChildItem Env: (Windows: set) Manages environment variables.

# Basic: View all variables
Get-ChildItem Env:
# Advanced: Add custom path
$env:PATH += ";C:\Tools"
  1. Get-CimInstance (Windows: wmic) Queries system details.

# Basic: Get CPU info
Get-CimInstance Win32_Processor | Select-Object Name
# Advanced: List installed software
Get-CimInstance Win32_Product | Select-Object Name, Version
  1. $env:USERNAME (Windows: whoami) Shows current user.

# Basic: Display username
$env:USERNAME
# Advanced: Get user SID
(Get-CimInstance Win32_ComputerSystem).UserName
  1. Get-Process (Windows: tasklist) Lists running processes.

# Basic: Show all processes
Get-Process
# Advanced: Filter specific process
Get-Process -Name notepad

Network Commands

  1. Get-NetIPAddress (Windows: ipconfig) Shows network configuration.

# Basic: Display IP details
Get-NetIPAddress
# Advanced: Refresh network adapter
Restart-NetAdapter -Name Ethernet
  1. Test-Connection (Windows: ping) Tests network connectivity.

# Basic: Ping a website
Test-Connection google.com
# Advanced: Continuous ping with timestamp
while ($true) { Test-Connection google.com -Count 1 | Select-Object @{n='Time';e={Get-Date}}, * }
  1. Test-NetConnection (Windows: tracert) Tests route to a host.

# Basic: Trace to domain
Test-NetConnection google.com -TraceRoute
# Advanced: Trace with no DNS
Test-NetConnection 8.8.8.8 -TraceRoute
  1. Get-NetTCPConnection (Windows: netstat) Shows network connections/ports.

# Basic: List active connections
Get-NetTCPConnection
# Advanced: Show process IDs
Get-NetTCPConnection | Select-Object LocalPort, OwningProcess
  1. Resolve-DnsName (Windows: nslookup) Queries DNS.

# Basic: Resolve domain
Resolve-DnsName google.com
# Advanced: Query specific DNS server
Resolve-DnsName google.com -Server 8.8.8.8
  1. Get-NetNeighbor (Windows: arp) Manages ARP cache.

# Basic: Show ARP table
Get-NetNeighbor
# Advanced: Remove ARP entry
Remove-NetNeighbor -IPAddress 192.168.1.1
  1. Get-NetRoute (Windows: route) Manages routing table.

# Basic: Display routing table
Get-NetRoute
# Advanced: Add persistent route
New-NetRoute -DestinationPrefix 10.0.0.0/24 -NextHop 192.168.1.1 -RouteMetric 1
  1. New-PSDrive (Windows: net use) Maps network drives.

# Basic: Map a drive
New-PSDrive -Name Z -PSProvider FileSystem -Root \\server\share
# Advanced: Map with credentials
New-PSDrive -Name Z -PSProvider FileSystem -Root \\server\share -Credential (Get-Credential)
  1. Get-NetTCPConnection -State Listen (Windows: netstat -an) Shows listening connections.

# Basic: List listening ports
Get-NetTCPConnection -State Listen
# Advanced: Log connections
Get-NetTCPConnection -State Listen | Out-File netlog.txt
  1. Set-NetIPInterface (Windows: netsh) Configures network settings.

# Basic: Show network interfaces
Get-NetIPInterface
# Advanced: Enable DHCP
Set-NetIPInterface -InterfaceAlias Wi-Fi -Dhcp Enabled

Disk and Drive Commands

  1. Repair-Volume (Windows: chkdsk) Checks/repairs disk errors.

# Basic: Scan drive
Repair-Volume -DriveLetter C
# Advanced: Fix errors offline
Repair-Volume -DriveLetter C -OfflineScanAndFix
  1. Get-Disk | New-Partition (Windows: diskpart) Manages disks/partitions.

# Basic: List disks
Get-Disk
# Advanced: Create partition
New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetter
  1. Initialize-Disk | Format-Volume (Windows: format) Formats a drive.

# Basic: Format to NTFS
Format-Volume -DriveLetter D -FileSystem NTFS
# Advanced: Quick format with label
Format-Volume -DriveLetter D -FileSystem NTFS -NewFileSystemLabel MyUSB -Force
  1. Set-Volume (Windows: label) Sets volume label.

# Basic: Change label
Set-Volume -DriveLetter D -NewFileSystemLabel MyDrive
# Advanced: Remove label
Set-Volume -DriveLetter D -NewFileSystemLabel ""
  1. Get-Volume (Windows: vol) Shows volume info.

# Basic: Display volume details
Get-Volume -DriveLetter C
# Advanced: Pipe to file
Get-Volume | Out-File volume.txt
  1. Optimize-Volume (Windows: fsutil) Manages filesystem properties.

# Basic: Check drive health
Get-Volume -DriveLetter C | Select-Object HealthStatus
# Advanced: Defragment drive
Optimize-Volume -DriveLetter C

Task and Process Management Commands

  1. Stop-Process (Windows: taskkill) Terminates processes.

# Basic: Stop process by name
Stop-Process -Name notepad
# Advanced: Force-stop by ID
Stop-Process -Id 1234 -Force
  • Investigation Context: Monitor in Defender XDR/Sentinel. KQL query:

DeviceProcessEvents
| where ProcessCommandLine contains "Stop-Process"
| project Timestamp, DeviceName, ProcessCommandLine
  1. Register-ScheduledTask (Windows: schtasks) Manages scheduled tasks.

# Basic: Create daily task
Register-ScheduledTask -TaskName MyTask -Action (New-ScheduledTaskAction -Execute notepad) -Trigger (New-ScheduledTaskTrigger -Daily -At 9AM)
# Advanced: Delete task
Unregister-ScheduledTask -TaskName MyTask -Confirm:$false
  1. Get-Service (Windows: sc) Controls services.

# Basic: Check service status
Get-Service -Name wuauserv
# Advanced: Restart service
Restart-Service -Name wuauserv -Force
  1. Stop-Computer (Windows: shutdown) Performs shutdown/restart.

# Basic: Shutdown in 60s
Stop-Computer -Delay 60
# Advanced: Cancel shutdown
Stop-Computer -Cancel
  1. Start-Process (Windows: start) Starts a program.

# Basic: Open Notepad
Start-Process notepad
# Advanced: Open URL in browser
Start-Process "https://google.com"
  1. Pause (Windows: pause) Pauses script execution.

# Basic: Pause script
Pause
# Advanced: Pause with message
Write-Host "Press Enter to continue..." ; Pause
  1. Start-Sleep (Windows: timeout) Adds delay in scripts.

# Basic: Wait 10 seconds
Start-Sleep -Seconds 10
# Advanced: Wait in milliseconds
Start-Sleep -Milliseconds 5000

User and Security Commands

  1. New-LocalUser (Windows: net user) Manages user accounts.

# Basic: Add user
New-LocalUser -Name JohnDoe -Password (ConvertTo-SecureString "Pass123" -AsPlainText -Force)
# Advanced: Disable user
Disable-LocalUser -Name JohnDoe
  1. Add-LocalGroupMember (Windows: net localgroup) Manages group memberships.

# Basic: Add to Administrators
Add-LocalGroupMember -Group Administrators -Member JohnDoe
# Advanced: List group members
Get-LocalGroupMember -Group Administrators
  1. Start-Process -Credential (Windows: runas) Runs command as another user.

# Basic: Run as user
Start-Process notepad -Credential (Get-Credential)
# Advanced: Run with saved credentials
Start-Process notepad -Credential (Import-Clixml cred.xml)
  1. Set-Acl (Windows: cacls) Modifies file permissions.

# Basic: Grant read access
$acl = Get-Acl file.txt; $acl.SetAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone","Read","Allow"))); Set-Acl file.txt $acl
# Advanced: Deny write access
$acl = Get-Acl file.txt; $acl.SetAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone","Write","Deny"))); Set-Acl file.txt $acl
  1. Set-Acl (Windows: icacls) Advanced file permissions.

# Basic: Grant full control
$acl = Get-Acl file.txt; $acl.SetAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule("Users","FullControl","Allow"))); Set-Acl file.txt $acl
# Advanced: Remove permissions
$acl = Get-Acl file.txt; $acl.RemoveAccessRuleAll((New-Object System.Security.AccessControl.FileSystemAccessRule("Users","FullControl","Allow"))); Set-Acl file.txt $acl
  1. Lock-Computer (Windows: lock) Locks workstation.

# Basic: Lock session
Lock-Computer
# Advanced: Lock in script
Write-Host "Locking..." ; Lock-Computer
  1. Update-GP (Windows: gpupdate) Updates Group Policy.

# Basic: Refresh policy
gpupdate
# Advanced: Force user and computer policy
gpupdate /force
  1. Set-GPRegistryValue (Windows: secedit) Applies security settings.

# Basic: Export GPO settings
Get-GPO -All | Export-Csv gpo.csv
# Advanced: Set registry policy
Set-GPRegistryValue -Name "Default Domain Policy" -Key "HKLM\Software\Policies" -ValueName "Test" -Type String -Value "Enabled"

Power and Shutdown Commands

  1. Get-CimInstance Win32_Battery (Windows: powercfg) Manages power settings.

# Basic: Show battery info
Get-CimInstance Win32_Battery
# Advanced: Export power report
powercfg /batteryreport; Get-Content battery-report.html
  1. Stop-Computer -Force (Windows: shutdown /s /t 0) Immediate shutdown.

# Basic: Shutdown now
Stop-Computer -Force
# Advanced: Shutdown with message
Stop-Computer -Force -Comment "System maintenance"
  1. Restart-Computer -Force (Windows: shutdown /r /t 0) Immediate restart.

# Basic: Restart now
Restart-Computer -Force
# Advanced: Restart with message
Restart-Computer -Force -Comment "Applying updates"
  1. Logoff (Windows: shutdown /l) Logs off user.

# Basic: Log off
logoff
# Advanced: Log off in script
Write-Host "Logging off..." ; logoff

Troubleshooting Commands

  1. Repair-WindowsImage (Windows: sfc /scannow) Repairs system files.

# Basic: Scan and repair
sfc /scannow
# Advanced: Verify specific file
sfc /verifyfile C:\Windows\System32\kernel32.dll
  1. Repair-WindowsImage (Windows: DISM) Repairs Windows images.

# Basic: Check health
Repair-WindowsImage -Online -CheckHealth
# Advanced: Restore health
Repair-WindowsImage -Online -RestoreHealth
  1. Clear-Disk (Windows: cleanmgr) Manages disk space.

# Basic: Run disk cleanup
cleanmgr
# Advanced: Auto-clean temporary files
cleanmgr /sagerun:1
  1. Get-WinEvent (Windows: eventvwr) Views event logs.

# Basic: Show recent logs
Get-WinEvent -LogName System -MaxEvents 10
# Advanced: Filter by event ID
Get-WinEvent -LogName System -FilterHashtable @{Id=4688}
  1. Get-ComputerInfo (Windows: msinfo32) Shows system info.

# Basic: Display system info
Get-ComputerInfo
# Advanced: Export to file
Get-ComputerInfo | Out-File sysinfo.txt

Advanced and Miscellaneous Commands

  1. Get-ChildItem -Recurse (Windows: tree) Displays folder structure.

# Basic: Show folder tree
Get-ChildItem -Path C:\Data | Format-Wide
# Advanced: Include files recursively
Get-ChildItem -Path C:\Data -Recurse
  1. Write-Output (Windows: echo) Displays messages or writes to files.

# Basic: Print message
Write-Output "Hello, World!"
# Advanced: Append to file
Write-Output "Log entry" | Out-File log.txt -Append
  1. Clear-Host (Windows: cls) Clears console screen.

# Basic: Clear screen
Clear-Host
# Advanced: Clear in script
Write-Host "Clearing..." ; Clear-Host
  1. $host.UI.RawUI.WindowTitle (Windows: title) Sets console title.

# Basic: Set title
$host.UI.RawUI.WindowTitle = "My Script"
# Advanced: Dynamic title
$host.UI.RawUI.WindowTitle = "Backup_$((Get-Date).ToString('yyyy-MM-dd'))"
  1. $PSStyle (Windows: colour) Changes console colours (PowerShell 7+).

# Basic: Green text
$PSStyle.Foreground.Green
# Advanced: Blue on white
$PSStyle.Foreground.Blue; $PSStyle.Background.White
  1. Exit (Windows: exit) Closes PowerShell session.

# Basic: Exit session
Exit
# Advanced: Exit with code
Exit 1
  1. $PSCommandPath (Windows: prompt) Customises PowerShell prompt.

# Basic: Set simple prompt
function prompt { "PS> " }
# Advanced: Custom colored prompt
function prompt { "$([char]27)[32m$env:USERNAME@$env:COMPUTERNAME> " }
  1. Get-Help (Windows: help) Shows command help.

# Basic: Help for Get-ChildItem
Get-Help Get-ChildItem
# Advanced: Search help topics
Get-Help *list*

Scripting and Shell Commands

  1. If (Windows: if) Conditional logic in scripts.

# Basic: Check file existence
if (Test-Path file.txt) { Write-Output "Found" }
# Advanced: Check command success
if ($LASTEXITCODE -eq 0) { Write-Output "Success" }
  1. ForEach-Object (Windows: for) Loops through values.

# Basic: List .txt files
Get-ChildItem *.txt | ForEach-Object { $_.Name }
# Advanced: Copy files recursively
Get-ChildItem -Recurse -Include *.txt | ForEach-Object { Copy-Item $_.FullName D:\Backup }
  1. Function (Windows: goto) Defines functions for script flow.

# Basic: Define function
function MyFunc { Write-Output "Done" }; MyFunc
# Advanced: Conditional function call
if ($LASTEXITCODE -eq 1) { function Error { Write-Output "Failed" }; Error } else { Write-Output "OK" }
  1. . (dot sourcing) (Windows: call) Calls another script/function.

# Basic: Source script
. .\myscript.ps1
# Advanced: Source with parameters
. .\myscript.ps1 -Arg1 value
  1. $script: / $local: (Windows: setlocal/endlocal) Manages variable scope.

# Basic: Local variable
function MyFunc { $local:var = 123; Write-Output $var }; MyFunc
# Advanced: Preserve variable
function MyFunc { $local:var = Get-Date; $var | Out-File out.txt }; MyFunc

Bonus Useful Commands

  1. Set-Clipboard (Windows: clip) Copies to clipboard.

# Basic: Copy dir output
Get-ChildItem | Set-Clipboard
# Advanced: Copy system info
Get-ComputerInfo | Set-Clipboard
  1. Select-String (Windows: find) Searches text in files.

# Basic: Find text
Select-String "error" log.txt
# Advanced: Case-insensitive recursive search
Select-String "error" -Path *.txt -Recurse -CaseSensitive:$false
  1. Get-ItemProperty (Windows: assoc) Manages file associations.

# Basic: Show .txt association
Get-ItemProperty HKLM:\Software\Classes\.txt
# Advanced: Set association
Set-ItemProperty HKLM:\Software\Classes\.txt -Name PerceivedType -Value text
  1. Get-CimInstance Win32_PnPSignedDriver (Windows: driverquery) Lists drivers.

# Basic: List drivers
Get-CimInstance Win32_PnPSignedDriver
# Advanced: Export to CSV
Get-CimInstance Win32_PnPSignedDriver | Export-Csv drivers.csv
  1. Show-Command explorer (Windows: taskview) Opens Task View (GUI-based).

# Basic: Launch Task View
explorer.exe shell:::{3080F90E-D7AD-11D9-BD98-0000947B0257}
# Advanced: Scripted launch
Write-Host "Opening Task View..." ; explorer.exe shell:::{3080F90E-D7AD-11D9-BD98-0000947B0257}

Last updated