# Set the service name (Service name is "Net Driver HPZ12" from your image)
$ServiceName = "Net Driver HPZ12"
# Set the log file path
$LogFile = "C:\Service_Monitor\$ServiceName_Status.log"
# Create the directory if it doesn't exist
$LogPath = Split-Path -Path $LogFile -Parent
if (-not (Test-Path $LogPath)) {
New-Item -Path $LogPath -ItemType Directory | Out-Null
}
# Variable to hold the last known status
$LastStatus = (Get-Service -Name $ServiceName).Status
# Initial log entry
$LogEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Initial Status: $LastStatus"
Add-Content -Path $LogFile -Value $LogEntry
Write-Host $LogEntry
# Start the continuous monitoring loop
while ($true) {
# Get the current service object and status
$Service = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
$CurrentStatus = $Service.Status
# Check for status change
if ($CurrentStatus -ne $LastStatus) {
$LogEntry = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') - Status Change: $LastStatus -> $CurrentStatus"
Add-Content -Path $LogFile -Value $LogEntry
Write-Host $LogEntry
# Update the last known status
$LastStatus = $CurrentStatus
}
# Wait for a set interval (e.g., 60 seconds) before checking again
Start-Sleep -Seconds 60
}
No comments:
Post a Comment