70+ Essential Powershell Commands
File and Directory Commands
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, LengthSet-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)"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 -ForceRemove-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 -ForceRemove-Item (Windows: del) Deletes files.
# Basic: Delete a file
Remove-Item -Path temp.txt
# Advanced: Delete all .log files silently
Remove-Item -Path *.log -ForceCopy-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 -ForceCopy-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 -ForceMove-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' }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)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
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$env:COMPUTERNAME (Windows: hostname) Shows computer name.
# Basic: Get hostname
$env:COMPUTERNAME
# Advanced: Log hostname
$env:COMPUTERNAME | Out-File device.txtGet-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"Get-ChildItem Env: (Windows: set) Manages environment variables.
# Basic: View all variables
Get-ChildItem Env:
# Advanced: Add custom path
$env:PATH += ";C:\Tools"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$env:USERNAME (Windows: whoami) Shows current user.
# Basic: Display username
$env:USERNAME
# Advanced: Get user SID
(Get-CimInstance Win32_ComputerSystem).UserNameGet-Process (Windows: tasklist) Lists running processes.
# Basic: Show all processes
Get-Process
# Advanced: Filter specific process
Get-Process -Name notepadNetwork Commands
Get-NetIPAddress (Windows: ipconfig) Shows network configuration.
# Basic: Display IP details
Get-NetIPAddress
# Advanced: Refresh network adapter
Restart-NetAdapter -Name EthernetTest-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}}, * }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 -TraceRouteGet-NetTCPConnection (Windows: netstat) Shows network connections/ports.
# Basic: List active connections
Get-NetTCPConnection
# Advanced: Show process IDs
Get-NetTCPConnection | Select-Object LocalPort, OwningProcessResolve-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.8Get-NetNeighbor (Windows: arp) Manages ARP cache.
# Basic: Show ARP table
Get-NetNeighbor
# Advanced: Remove ARP entry
Remove-NetNeighbor -IPAddress 192.168.1.1Get-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 1New-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)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.txtSet-NetIPInterface (Windows: netsh) Configures network settings.
# Basic: Show network interfaces
Get-NetIPInterface
# Advanced: Enable DHCP
Set-NetIPInterface -InterfaceAlias Wi-Fi -Dhcp EnabledDisk and Drive Commands
Repair-Volume (Windows: chkdsk) Checks/repairs disk errors.
# Basic: Scan drive
Repair-Volume -DriveLetter C
# Advanced: Fix errors offline
Repair-Volume -DriveLetter C -OfflineScanAndFixGet-Disk | New-Partition (Windows: diskpart) Manages disks/partitions.
# Basic: List disks
Get-Disk
# Advanced: Create partition
New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetterInitialize-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 -ForceSet-Volume (Windows: label) Sets volume label.
# Basic: Change label
Set-Volume -DriveLetter D -NewFileSystemLabel MyDrive
# Advanced: Remove label
Set-Volume -DriveLetter D -NewFileSystemLabel ""Get-Volume (Windows: vol) Shows volume info.
# Basic: Display volume details
Get-Volume -DriveLetter C
# Advanced: Pipe to file
Get-Volume | Out-File volume.txtOptimize-Volume (Windows: fsutil) Manages filesystem properties.
# Basic: Check drive health
Get-Volume -DriveLetter C | Select-Object HealthStatus
# Advanced: Defragment drive
Optimize-Volume -DriveLetter CTask and Process Management Commands
Stop-Process (Windows: taskkill) Terminates processes.
# Basic: Stop process by name
Stop-Process -Name notepad
# Advanced: Force-stop by ID
Stop-Process -Id 1234 -ForceInvestigation Context: Monitor in Defender XDR/Sentinel. KQL query:
DeviceProcessEvents
| where ProcessCommandLine contains "Stop-Process"
| project Timestamp, DeviceName, ProcessCommandLineRegister-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:$falseGet-Service (Windows: sc) Controls services.
# Basic: Check service status
Get-Service -Name wuauserv
# Advanced: Restart service
Restart-Service -Name wuauserv -ForceStop-Computer (Windows: shutdown) Performs shutdown/restart.
# Basic: Shutdown in 60s
Stop-Computer -Delay 60
# Advanced: Cancel shutdown
Stop-Computer -CancelStart-Process (Windows: start) Starts a program.
# Basic: Open Notepad
Start-Process notepad
# Advanced: Open URL in browser
Start-Process "https://google.com"Pause (Windows: pause) Pauses script execution.
# Basic: Pause script
Pause
# Advanced: Pause with message
Write-Host "Press Enter to continue..." ; PauseStart-Sleep (Windows: timeout) Adds delay in scripts.
# Basic: Wait 10 seconds
Start-Sleep -Seconds 10
# Advanced: Wait in milliseconds
Start-Sleep -Milliseconds 5000User and Security Commands
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 JohnDoeAdd-LocalGroupMember (Windows: net localgroup) Manages group memberships.
# Basic: Add to Administrators
Add-LocalGroupMember -Group Administrators -Member JohnDoe
# Advanced: List group members
Get-LocalGroupMember -Group AdministratorsStart-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)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 $aclSet-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 $aclLock-Computer (Windows: lock) Locks workstation.
# Basic: Lock session
Lock-Computer
# Advanced: Lock in script
Write-Host "Locking..." ; Lock-ComputerUpdate-GP (Windows: gpupdate) Updates Group Policy.
# Basic: Refresh policy
gpupdate
# Advanced: Force user and computer policy
gpupdate /forceSet-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
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.htmlStop-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"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"Logoff (Windows: shutdown /l) Logs off user.
# Basic: Log off
logoff
# Advanced: Log off in script
Write-Host "Logging off..." ; logoffTroubleshooting Commands
Repair-WindowsImage (Windows: sfc /scannow) Repairs system files.
# Basic: Scan and repair
sfc /scannow
# Advanced: Verify specific file
sfc /verifyfile C:\Windows\System32\kernel32.dllRepair-WindowsImage (Windows: DISM) Repairs Windows images.
# Basic: Check health
Repair-WindowsImage -Online -CheckHealth
# Advanced: Restore health
Repair-WindowsImage -Online -RestoreHealthClear-Disk (Windows: cleanmgr) Manages disk space.
# Basic: Run disk cleanup
cleanmgr
# Advanced: Auto-clean temporary files
cleanmgr /sagerun:1Get-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}Get-ComputerInfo (Windows: msinfo32) Shows system info.
# Basic: Display system info
Get-ComputerInfo
# Advanced: Export to file
Get-ComputerInfo | Out-File sysinfo.txtAdvanced and Miscellaneous Commands
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 -RecurseWrite-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 -AppendClear-Host (Windows: cls) Clears console screen.
# Basic: Clear screen
Clear-Host
# Advanced: Clear in script
Write-Host "Clearing..." ; Clear-Host$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'))"$PSStyle (Windows: colour) Changes console colours (PowerShell 7+).
# Basic: Green text
$PSStyle.Foreground.Green
# Advanced: Blue on white
$PSStyle.Foreground.Blue; $PSStyle.Background.WhiteExit (Windows: exit) Closes PowerShell session.
# Basic: Exit session
Exit
# Advanced: Exit with code
Exit 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> " }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
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" }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 }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" }. (dot sourcing) (Windows: call) Calls another script/function.
# Basic: Source script
. .\myscript.ps1
# Advanced: Source with parameters
. .\myscript.ps1 -Arg1 value$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 }; MyFuncBonus Useful Commands
Set-Clipboard (Windows: clip) Copies to clipboard.
# Basic: Copy dir output
Get-ChildItem | Set-Clipboard
# Advanced: Copy system info
Get-ComputerInfo | Set-ClipboardSelect-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:$falseGet-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 textGet-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.csvShow-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