PowerShell Scripting: Automate Windows Administration
Essential PowerShell scripts and techniques for Windows administrators. Covers user management, system info gathering, log analysis, and task automation.
PowerShell Scripting: Automate Windows Administration
PowerShell is the most powerful tool in a Windows admin's arsenal. This guide covers practical scripts you'll use every day.
Getting Started
# Check PowerShell version
$PSVersionTable.PSVersionSet execution policy (required once)
Set-ExecutionPolicy RemoteSigned -Scope CurrentUserSystem Information
# Quick system overview
Get-ComputerInfo | Select-Object CsName, OsName, OsVersion, CsProcessors, CsTotalPhysicalMemoryDisk space report
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)}},
@{N='Free%';E={[math]::Round($_.FreeSpace/$_.Size*100,1)}}Uptime
(Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTimeUser Management
# List all AD users
Get-ADUser -Filter * -Properties LastLogonDate |
Select-Object Name, SamAccountName, LastLogonDate, Enabled |
Sort-Object LastLogonDate -DescendingFind inactive users (90+ days)
$cutoff = (Get-Date).AddDays(-90)
Get-ADUser -Filter {LastLogonDate -lt $cutoff -and Enabled -eq $true} -Properties LastLogonDate |
Select-Object Name, SamAccountName, LastLogonDateCreate a new AD user
New-ADUser -Name "John Doe" -SamAccountName "jdoe" -UserPrincipalName "[email protected]"
-Path "OU=Users,DC=domain,DC=com" -AccountPassword (ConvertTo-SecureString "P@ssw0rd123!" -AsPlainText -Force)
-Enabled $true -ChangePasswordAtLogon $trueBulk create users from CSV
Import-Csv users.csv | ForEach-Object {
New-ADUser -Name "$($_.FirstName) $($_.LastName)"
-SamAccountName $_.Username
-UserPrincipalName "$($_.Username)@domain.com"
-AccountPassword (ConvertTo-SecureString $_.Password -AsPlainText -Force)
-Enabled $true
}Service Management
# Check service status
Get-Service | Where-Object {$_.Status -eq 'Running'} | Sort-Object DisplayNameRestart a service
Restart-Service -Name "Spooler" -ForceMonitor a service and restart if stopped
$service = "ImportantService"
if ((Get-Service $service).Status -ne 'Running') {
Start-Service $service
Send-MailMessage -To "[email protected]" -Subject "$service was restarted"
-Body "Service was found stopped and restarted at $(Get-Date)"
-SmtpServer "mail.company.com"
}Log Analysis
# Find failed login attempts
Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625} -MaxEvents 50 |
Select-Object TimeCreated,
@{N='User';E={$_.Properties[5].Value}},
@{N='Source';E={$_.Properties[19].Value}}Check for errors in the last 24 hours
Get-WinEvent -FilterHashtable @{LogName='System'; Level=2; StartTime=(Get-Date).AddDays(-1)} |
Select-Object TimeCreated, ProviderName, Message | Format-Table -WrapExport events to CSV
Get-WinEvent -FilterHashtable @{LogName='Application'; Level=2,3} -MaxEvents 100 |
Export-Csv "C:\logs\app-errors.csv" -NoTypeInformationNetwork Diagnostics
# Check open ports
Get-NetTCPConnection -State Listen |
Select-Object LocalPort, OwningProcess,
@{N='Process';E={(Get-Process -Id $_.OwningProcess).Name}} |
Sort-Object LocalPortDNS lookup
Resolve-DnsName google.com -Type APing sweep a subnet
1..254 | ForEach-Object -Parallel {
if (Test-Connection "192.168.1.$_" -Count 1 -Quiet -TimeoutSeconds 1) {
"192.168.1.$_ is alive"
}
} -ThrottleLimit 50Practical Scripts
Daily report email:
$report = @"
Server: $env:COMPUTERNAME
Date: $(Get-Date)
Uptime: $((Get-Date) - (Get-CimInstance Win32_OperatingSystem).LastBootUpTime)
CPU: $((Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue)%
Free Disk: $([math]::Round((Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'").FreeSpace/1GB,2))GB
"@Send-MailMessage -To "[email protected]" -Subject "Daily Report - $env:COMPUTERNAME" `
-Body $report -SmtpServer "mail.company.com"
Conclusion
These scripts handle 80% of daily Windows admin tasks. Save them in a scripts folder, customize for your environment, and schedule the recurring ones with Task Scheduler. PowerShell turns hours of clicking into seconds of automation.