PowerShell is a powerful scripting language and automation tool for Windows systems. You can use it to monitor system resources like CPU usage, memory utilization, disk space, and more. Here are some common tasks and examples for monitoring system resources using PowerShell:
Check CPU Usage: To monitor CPU usage, you can use the Get-Counter
cmdlet. Here’s an example that checks CPU usage every 2 seconds and displays it in real-time:
while ($true) {
$cpuUsage = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
Write-Host "CPU Usage: $cpuUsage%"
Start-Sleep -Seconds 2
}
Monitor Memory Usage: You can use Get-Counter
to monitor memory usage as well. This example checks both available memory and committed memory:
while ($true) {
$memory = Get-Counter '\Memory\Available MBytes'
$committedMemory = Get-Counter '\Memory\Committed Bytes'
Write-Host "Available Memory: $($memory.CounterSamples.CookedValue) MB"
Write-Host "Committed Memory: $($committedMemory.CounterSamples.CookedValue) Bytes"
Start-Sleep -Seconds 2
}
Check Disk Space: To monitor disk space, you can use Get-WmiObject
to query the Win32_LogicalDisk class:
$disks = Get-WmiObject -Class Win32_LogicalDisk | Where-Object { $_.DriveType -eq 3 }
foreach ($disk in $disks) {
$driveLetter = $disk.DeviceID
$freeSpace = [math]::Round($disk.FreeSpace / 1GB, 2)
$totalSpace = [math]::Round($disk.Size / 1GB, 2)
Write-Host "Drive $driveLetter - Free Space: ${freeSpace}GB / Total Space: ${totalSpace}GB"
}
Monitor Network Usage: You can use Get-Counter
to monitor network interface statistics. This example tracks network traffic on a specific network interface:
$networkInterface = "Ethernet"
while ($true) {
$networkStats = Get-Counter "\Network Interface($networkInterface)\Bytes Total/sec"
Write-Host "Network Usage on $networkInterface: $($networkStats.CounterSamples.CookedValue) bytes/second"
Start-Sleep -Seconds 2
}
These are just a few examples of how you can use PowerShell to monitor system resources. You can customize and expand these scripts to fit your specific monitoring needs, and you can also schedule them to run as background tasks or integrate them into your existing monitoring systems.