As a system administrator, having a reliable toolkit of PowerShell scripts can significantly improve your efficiency and consistency in managing Windows environments. Here’s a collection of essential PowerShell scripts that every admin should have in their arsenal.
function Get-SystemHealthStatus {
[CmdletBinding()]
param()
$report = @{
DiskSpace = Get-WmiObject -Class Win32_LogicalDisk |
Select-Object DeviceID, @{Name='FreeSpace(GB)';Expression={[math]::Round($_.FreeSpace/1GB, 2)}}
Memory = Get-WmiObject -Class Win32_OperatingSystem |
Select-Object @{Name='FreeMemory(GB)';Expression={[math]::Round($_.FreePhysicalMemory/1MB, 2)}}
CPU = Get-WmiObject -Class Win32_Processor |
Select-Object LoadPercentage
Services = Get-Service | Where-Object {$_.Status -eq 'Stopped' -and $_.StartType -eq 'Automatic'}
LastBoot = Get-WmiObject -Class Win32_OperatingSystem |
Select-Object @{Name='LastBootTime';Expression={$_.ConvertToDateTime($_.LastBootUpTime)}}
}
return $report
}
This script provides a comprehensive overview of system health, including disk space, memory usage, CPU load, stopped services, and system uptime.
function Backup-ImportantData {
param(
[string]$SourcePath,
[string]$BackupPath,
[string[]]$ExcludePatterns
)
$date = Get-Date -Format "yyyy-MM-dd_HHmm"
$backupFolder = Join-Path $BackupPath "Backup_$date"
if (!(Test-Path $backupFolder)) {
New-Item -ItemType Directory -Path $backupFolder
}
$robocopyArgs = @(
$SourcePath,
$backupFolder,
'/MIR',
'/Z',
'/W:1',
'/R:3',
'/LOG:backup_log.txt'
)
foreach ($pattern in $ExcludePatterns) {
$robocopyArgs += "/XF $pattern"
}
& robocopy @robocopyArgs
}
This backup script uses Robocopy for reliable data transfer with error handling and logging capabilities.
function New-SecureUser {
param(
[Parameter(Mandatory=$true)]
[string]$Username,
[Parameter(Mandatory=$true)]
[SecureString]$Password,
[string[]]$Groups = @('Users'),
[bool]$MustChangePassword = $true
)
try {
$userParams = @{
Name = $Username
Password = $Password
PasswordNeverExpires = $false
UserMayNotChangePassword = $false
PasswordMustChange = $MustChangePassword
Enabled = $true
}
New-LocalUser @userParams
foreach ($group in $Groups) {
Add-LocalGroupMember -Group $group -Member $Username
}
Write-Host "User $Username created successfully and added to specified groups"
}
catch {
Write-Error "Failed to create user: $_"
}
}
This script provides a secure way to create new user accounts with proper password policies and group assignments.
When working with these administrative scripts, always follow these key principles:
Consider these automation opportunities:
Remember to always run these scripts with appropriate administrative privileges and maintain a changelog for any modifications made to production scripts.
These PowerShell scripts form a solid foundation for system administration tasks. By customizing and expanding upon these examples, you can build a comprehensive toolkit tailored to your organization’s specific needs.