2.5 - ממשק WMI - פתרון
פתרון: מערכת ניהול משאבים עם WMI ב-PowerShell
חלק 1: הצגת פרטי מערכת
# Operating system version
$os = Get-WmiObject -Class Win32_OperatingSystem
Write-Host "Operating system: $($os.Caption) Version: $($os.Version)"
# CPU information
$cpu = Get-WmiObject -Class Win32_Processor
Write-Host "CPU: $($cpu.Name), Speed: $($cpu.MaxClockSpeed) MHz, Cores: $($cpu.NumberOfCores)"
# Amount of physical memory
$memory = Get-WmiObject -Class Win32_PhysicalMemory
$totalMemory = ($memory.Capacity | Measure-Object -Sum).Sum / 1GB
Write-Host "Physical memory: $([math]::round($totalMemory, 2)) GB"
# Hard disk information
$disk = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3"
$disk | ForEach-Object {
Write-Host "Disk: $($_.DeviceID), Size: $([math]::round($_.Size / 1GB, 2)) GB, Free space: $([math]::round($_.FreeSpace / 1GB, 2)) GB"
}
חלק 2: מעקב אחר processes
# Display running processes
$processes = Get-WmiObject -Class Win32_Process
$processes | Select-Object Name, ProcessId, @{Name="CPU";Expression={($_.PercentProcessorTime)}}, @{Name="MemoryUsage";Expression={($_.WorkingSetSize / 1MB)}}
# Stop a process by PID
$pid = Read-Host "Enter the PID of the process you want to stop"
Stop-Process -Id $pid
Write-Host "Process $pid stopped."
חלק 3: התראות על שימוש במעבד
# Check CPU usage
$cpuUsage = Get-WmiObject -Class Win32_Processor
if ($cpuUsage.LoadPercentage -gt 80) {
Write-Host "High CPU usage: $($cpuUsage.LoadPercentage)%"
}
חלק 4: ניהול שירותים
# Display running services
$services = Get-WmiObject -Class Win32_Service
$services | Select-Object Name, State, StartMode
# Start or stop a service
$serviceName = Read-Host "Enter the name of the service to stop or start"
$action = Read-Host "Do you want to start or stop the service? (start/stop)"
if ($action -eq "start") {
Start-Service -Name $serviceName
Write-Host "The service $serviceName started."
} elseif ($action -eq "stop") {
Stop-Service -Name $serviceName
Write-Host "The service $serviceName stopped."
}
הסבר כללי:
- חלק 1: קוד זה מבצע שאילתות WMI כדי להוציא מידע על מערכת ההפעלה, המעבד, הזיכרון והדיסק הקשיח.
- חלק 2: מציג את הprocesses הרצים במערכת ומאפשר להפסיק process על פי PID שנבחר על ידי המשתמש.
- חלק 3: בודק אם השימוש במעבד עולה על 80% ומציג התראה אם כן.
- חלק 4: מציג את השירותים הרצים במערכת ומאפשר למשתמש להפעיל או להפסיק שירותים מסוימים.