PowerShell Çıktılarınızı Web Sayfası Olarak Görüntüleyin
PowerShell ile PSWriteHTML modülünün nasıl kullanıldığına bir önceki makalemizde değinmiştim. Şimdi custom olarak hazırlamış olduğum bir serverhealth scriptini IIS üzerinden yayınlama işleminden bahsedeceğim.
- Bu senaryoda script ilk olarak Active Directory ortamında yer alan server işletim sistemine sahip cihazları çekecek ve aktif olanları C:\Temp\UpServers.txt dosyasına yazdıracağız.
- Daha sonra bu dosyayı kullanarak ilgili makineler üzerinde tek tek serverhealth scriptini çalıştıracağız. HTML formatında bir çıktı üretilecek.
- Son olarak bu HTML dosyası IIS ile yayınlanacaktır.
İçindekiler
PowerShell ile Aktif Sunucuların Tespiti
NOT: Bu scriptin çalışacağı sunucuda Active Directory modülü yüklü olması ve ilgili sunuculara WinRM üzerinden erişilmesi gerekmektedir. Eğer bunlar yoksa script çalıştırmadan önce ilgili erişimlerin sağlanması gerekmektedir.
NOT: Aşağıdaki scriptleri production ortamdan önce test ortamında denemenizi öneririm. Herhangi bir set komutu ya da veri işleme adımı bulunmuyor. Ancak büyük domain ortamlarında aktif cihazları belirlemek için ping atılması ve dosyaya yazdırılması performans sorunlarına yol açabilir. Bu script özelleştirilebilir farklı scriptlerde kullanılabilir. Burada amaç PSWriteHTML modülünün bize kazandırdıklarını anlatmaktır.
# Get all computers from Active Directory that have 'Server' in their OS
$servers = Get-ADComputer -Filter * | ForEach-Object {
$os = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $_.Name).Caption
if ($os -like "*Server*") {
$_.Name
}
} | Where-Object { $_ -ne $null }
# Paths for output files
$upServersFile = "C:\Temp\UpServer.txt"
$downServersFile = "C:\Temp\DownServer.txt"
# Initialize empty arrays for Up and Down servers
$upServers = @()
$downServers = @()
# Ping each server and categorize based on response
foreach ($server in $servers) {
$pingResult = Test-Connection -ComputerName $server -Count 1 -Quiet
if ($pingResult) {
Write-Host "$server is online. Adding to UpServer.txt."
$upServers += $server
} else {
Write-Host "$server is offline. Adding to DownServer.txt."
$downServers += $server
}
}
# Save the results to the respective text files
$upServers | Out-File -FilePath $upServersFile
$downServers | Out-File -FilePath $downServersFile
Write-Host "Servers that are up are saved to: $upServersFile"
Write-Host "Servers that are down are saved to: $downServersFile"
Erişilebilir Sunucuların Listesi
C:\Temp\UPServer.txt dosyasını kontrol ettiğimizde erişebilir cihazlar (şu an scriptin çalıştırıldığı sunucundan) listelenmiştir.


PowerShell ile Server Health Scriptinin Çalıştırılması
Script ilgili sunuculardaki işlemleri gerçekleştirip “C:\inetpub\wwwroot\ServerHealth\ServerHealthReport.html” dizinine HTML dosyası oluşturacaktır.
# Import server names from UpServer.txt
$servers = Get-Content -Path "C:\Temp\UpServer.txt"
# Create an array for storing all health data
$healthData = @()
# Record the start time of the script
$scriptStartTime = Get-Date
# Iterate over each server from the UpServer.txt
foreach ($server in $servers) {
try {
Write-Host "Gathering health data for $server..."
# Get CPU Usage
$cpuUsage = Get-WmiObject -Class Win32_Processor -ComputerName $server | Select-Object -ExpandProperty LoadPercentage
# Get Memory Usage
$memory = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $server
$totalMemory = [math]::round($memory.TotalVisibleMemorySize / 1MB, 2)
$freeMemory = [math]::round($memory.FreePhysicalMemory / 1MB, 2)
$usedMemory = $totalMemory - $freeMemory
$memoryUsage = [math]::round(($usedMemory / $totalMemory) * 100, 2)
# Get Disk Usage
$disk = Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $server
$diskInfo = $disk | ForEach-Object {
@{
"Disk Usage" = "$($_.DeviceID): $([math]::round((($_.Size - $_.FreeSpace) / $_.Size) * 100, 2))% used"
}
}
# Get Network Adapter Information (IPv4 only)
$networkAdapters = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -ComputerName $server | Where-Object { $_.IPEnabled -eq $true }
$ipv4Address = $networkAdapters | ForEach-Object {
$_.IPAddress | Where-Object { $_ -match "^\d{1,3}(\.\d{1,3}){3}$" } # Match IPv4 addresses
}
$networkIP = $ipv4Address -join ', '
# Get MAC Address
$macAddress = ($networkAdapters | Select-Object -First 1).MACAddress
# Get Logon User Name (Last Logon User)
$logonUserName = (Get-WmiObject -Class Win32_NetworkLoginProfile -ComputerName $server | Sort-Object LastLogon -Descending | Select-Object -First 1).Name
# Get System Uptime
$uptime = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $server).LastBootUpTime
# Check if LastBootUpTime is a DateTime object, if not, convert it
if ($uptime -is [String]) {
# If LastBootUpTime is a string, attempt to parse it
$uptimeDateTime = [System.Management.ManagementDateTimeConverter]::ToDateTime($uptime)
} else {
# If it's already a DateTime, use it directly
$uptimeDateTime = $uptime
}
# Calculate the uptime duration
$currentDate = Get-Date
$uptimeDuration = $currentDate - $uptimeDateTime
# Format uptime as days, hours, minutes
$uptimeFormatted = "{0} days {1} hours {2} minutes" -f $uptimeDuration.Days, $uptimeDuration.Hours, $uptimeDuration.Minutes
# Get current time (for Script Run Time)
$scriptRunTime = Get-Date
$scriptRunTimeFormatted = $scriptRunTime.ToString("yyyy-MM-dd HH:mm:ss")
# Collect the data in an object
$healthData += [PSCustomObject]@{
"Server Name" = $server
"CPU Usage" = "$cpuUsage%"
"Memory Usage" = "$memoryUsage% ($usedMemory GB used of $totalMemory GB)"
"Disk Usage" = ($diskInfo | ForEach-Object { $_.'Disk Usage' }) -join ', '
"Network IP" = $networkIP
"MAC Address" = $macAddress
"Logon UserName" = $logonUserName
"System Uptime" = $uptimeFormatted
"Script Run Time" = $scriptRunTimeFormatted
}
} catch {
Write-Host "Could not retrieve data for $server. Error: $_"
}
}
# Use PSWriteHTML to create an HTML report
$healthData | Out-HTMLView -Title "Server Health Report" -FilePath "C:\inetpub\wwwroot\ServerHealth\ServerHealthReport.html" -AutoSize
Write-Host "HTML report saved to C:\ServerHealthReport.html"
Server Health Scriptinin Çıktısı
Script çıktısı aşağıdaki gibi olacaktır.

Bu scripti task schedule ile düzenli çalışacak hale getirebilirsiniz.
IIS Entegrasyonunu
IIS olan bir sunucuda ya da yeniden IIS yükleyerek boş bir WebSite oluşturup ilgili HTML dosyasını publish edebilirsiniz.


Ben test ortamımda serverhealth.contoso.com isminde bir sertifika oluşturdum ve assign ettim. HTTPS zorunlu değildir😊


Sonuç
DNS kaydını da tamamladıktan sonra web browser üzerinden ilgili adrese erişiyorum. Böylelikle schedule olarak çalışan scriptini dinamik olarak görüntüleme imkanı sağlamış olduk.

Bu tarz süreklilik gerektiren ve interaktif olması beklenen çıktıları veritabanına yazdırıp oradan da yayınlanabilir. Ancak temel düzeyde bu işlemleri yapmak için basit bir modül ve IIS yeterli olacaktır.
Faydalı olmaı dileğiyle, bilgihouse.com’u takip etmeyi unuymayın.