Windows Server
PowerShell for Server Management
Essential PowerShell commands and scripts for managing Windows Server, processes, services, disks, networking, and automation
PowerShell is the primary tool for managing Windows Server from the command line. This guide covers the essential commands for day-to-day server administration.
Execution policy
By default, PowerShell restricts script execution. Enable it for the current session or permanently:
# Current session only
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
# Permanently for current user
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned
# System-wide (requires admin)
Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSignedSystem information
# OS version and build
Get-ComputerInfo | Select-Object WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
# Uptime
(Get-Date) - (gcim Win32_OperatingSystem).LastBootUpTime
# CPU info
Get-WmiObject Win32_Processor | Select-Object Name, NumberOfCores, MaxClockSpeed
# RAM
Get-WmiObject Win32_ComputerSystem | Select-Object @{N='RAM_GB';E={[math]::Round($_.TotalPhysicalMemory/1GB,2)}}Process management
# List all processes sorted by CPU
Get-Process | Sort-Object CPU -Descending | Select-Object -First 20
# Find a specific process
Get-Process -Name nginx
# Kill a process
Stop-Process -Name notepad
Stop-Process -Id 1234
# Kill all instances of a process
Get-Process -Name mysqld | Stop-Process
# Start a process
Start-Process -FilePath "C:\nginx\nginx.exe" -WorkingDirectory "C:\nginx"Service management
# List all services
Get-Service | Sort-Object Status
# Filter by status
Get-Service | Where-Object { $_.Status -eq 'Running' }
Get-Service | Where-Object { $_.Status -eq 'Stopped' }
# Get a specific service
Get-Service -Name "W3SVC"
# Start / stop / restart
Start-Service -Name "nginx"
Stop-Service -Name "nginx"
Restart-Service -Name "nginx"
# Set startup type
Set-Service -Name "nginx" -StartupType Automatic
Set-Service -Name "nginx" -StartupType Disabled
# Check if a service exists
Get-Service -Name "nginx" -ErrorAction SilentlyContinueDisk and storage
# Disk usage
Get-PSDrive -PSProvider FileSystem | Select-Object Name, @{N='Used_GB';E={[math]::Round($_.Used/1GB,2)}}, @{N='Free_GB';E={[math]::Round($_.Free/1GB,2)}}
# Get all logical disks
Get-WmiObject Win32_LogicalDisk | Select-Object DeviceID, @{N='Size_GB';E={[math]::Round($_.Size/1GB,2)}}, @{N='Free_GB';E={[math]::Round($_.FreeSpace/1GB,2)}}
# Find large files (over 500 MB)
Get-ChildItem -Path C:\ -Recurse -ErrorAction SilentlyContinue |
Where-Object { $_.Length -gt 500MB } |
Sort-Object Length -Descending |
Select-Object FullName, @{N='Size_MB';E={[math]::Round($_.Length/1MB,0)}}
# Disk performance
Get-Counter '\PhysicalDisk(*)\% Disk Time' -SampleInterval 2 -MaxSamples 5Networking
# Show IP configuration (like ipconfig)
Get-NetIPAddress | Where-Object { $_.AddressFamily -eq 'IPv4' }
# Show all network adapters
Get-NetAdapter | Select-Object Name, Status, LinkSpeed, MacAddress
# Show routing table
Get-NetRoute | Where-Object { $_.DestinationPrefix -ne '255.255.255.255/32' }
# DNS configuration
Get-DnsClientServerAddress
# Set DNS servers
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses ("1.1.1.1","8.8.8.8")
# Test connectivity
Test-NetConnection -ComputerName google.com -Port 443
Test-NetConnection -ComputerName 8.8.8.8 -InformationLevel Detailed
# Show open ports (like netstat)
Get-NetTCPConnection | Where-Object { $_.State -eq 'Listen' } | Sort-Object LocalPort
# Flush DNS cache
Clear-DnsClientCacheFirewall management
# List firewall rules
Get-NetFirewallRule | Where-Object { $_.Enabled -eq 'True' } | Select-Object DisplayName, Direction, Action
# Add inbound rule (allow port)
New-NetFirewallRule -DisplayName "Allow HTTP" -Direction Inbound -Protocol TCP -LocalPort 80 -Action Allow
# Add inbound rule for a specific IP
New-NetFirewallRule -DisplayName "Allow SSH from Office" -Direction Inbound -Protocol TCP -LocalPort 22 -RemoteAddress "203.0.113.10" -Action Allow
# Remove a rule
Remove-NetFirewallRule -DisplayName "Allow HTTP"
# Disable/enable a rule
Disable-NetFirewallRule -DisplayName "Allow HTTP"
Enable-NetFirewallRule -DisplayName "Allow HTTP"File and folder operations
# List directory contents
Get-ChildItem C:\inetpub\wwwroot
# Copy files
Copy-Item -Path C:\source\file.txt -Destination C:\dest\
# Move files
Move-Item -Path C:\old\file.txt -Destination C:\new\file.txt
# Delete files older than 30 days
Get-ChildItem -Path C:\Logs -Recurse |
Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
Remove-Item -Force
# Create a directory
New-Item -ItemType Directory -Path C:\myapp\logs
# Get folder size
(Get-ChildItem -Path C:\inetpub -Recurse | Measure-Object -Property Length -Sum).Sum / 1GBEvent logs
# View recent System errors
Get-EventLog -LogName System -EntryType Error -Newest 20
# View Application log
Get-EventLog -LogName Application -Newest 50 | Select-Object TimeGenerated, Source, Message
# Search by event ID
Get-EventLog -LogName Security -InstanceId 4625 -Newest 20 # Failed logins
# Modern approach (Windows 2012+)
Get-WinEvent -LogName "System" -MaxEvents 50 | Where-Object { $_.Level -eq 2 }
# Export logs to CSV
Get-EventLog -LogName Application -Newest 1000 | Export-Csv C:\logs\app-events.csv -NoTypeInformationScheduled tasks
# List all scheduled tasks
Get-ScheduledTask | Select-Object TaskName, State, TaskPath
# Create a scheduled task (run script daily at 3 AM)
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\scripts\backup.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "03:00"
Register-ScheduledTask -TaskName "DailyBackup" -Action $action -Trigger $trigger -RunLevel Highest
# Run a task immediately
Start-ScheduledTask -TaskName "DailyBackup"
# Remove a task
Unregister-ScheduledTask -TaskName "DailyBackup" -Confirm:$falseUser management
# List local users
Get-LocalUser
# Create a user
New-LocalUser -Name "webadmin" -Password (ConvertTo-SecureString "Password123!" -AsPlainText -Force) -FullName "Web Admin"
# Add user to Administrators group
Add-LocalGroupMember -Group "Administrators" -Member "webadmin"
# Disable a user
Disable-LocalUser -Name "webadmin"
# Remove a user
Remove-LocalUser -Name "webadmin"Useful one-liners
# Top 10 CPU-consuming processes
Get-Process | Sort-Object CPU -Desc | Select-Object -First 10 Name, CPU, WorkingSet
# Restart server in 5 minutes
Restart-Computer -Delay 5
# Cancel pending restart
Shutdown /a
# Check Windows license status
(Get-WmiObject SoftwareLicensingProduct | Where-Object { $_.LicenseStatus -eq 1 }).Name
# Get list of installed software
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |
Select-Object DisplayName, DisplayVersion, Publisher | Sort-Object DisplayName
# Check IIS application pool status
Import-Module WebAdministration
Get-WebConfiguration "system.applicationHost/applicationPools/add" | Select-Object name, state