Private/Check-SystemState.ps1

<#
.SYNOPSIS
    Checks if a specified service on a computer is operational.
 
.DESCRIPTION
    This function attempts to verify if a computer is responsive and if a specified service is actively running. It continuously checks the system's WMI accessibility and the service status until the service is running or a timeout occurs.
 
.PARAMETER ComputerName
    The name of the computer to check.
 
.PARAMETER ServiceName
    The name of the service to check for running status.
 
.PARAMETER TimeoutSeconds
    The maximum time in seconds to wait for the system and service to become responsive.
 
.EXAMPLE
    Check-SystemState -ComputerName "Server01" -ServiceName "loginagent" -TimeoutSeconds 100
    Checks if the "loginagent" service on "Server01" is running, with a timeout of 100 seconds.
 
.NOTES
    Ensure that the computer is accessible over the network and that WMI services are enabled.
#>


Function Check-SystemState {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ComputerName,

        [Parameter(Mandatory = $true)]
        [string]$ServiceName,

        [int]$TimeoutSeconds = 100
    )

    $startTime = [datetime]::Now

    while (!(Get-WmiObject Win32_Bios -ComputerName $ComputerName -ErrorAction SilentlyContinue)) {
        Start-Sleep -Seconds 5
        if (([datetime]::Now - $startTime).TotalSeconds -gt $TimeoutSeconds) {
            Write-Output "Connection to $ComputerName timed out."
            return $false
        }
    }

    Write-Output "$ComputerName is responsive. Checking if the 'loginagent' service is started."
    do {
        $service = Get-Service -ComputerName $ComputerName -Name $ServiceName -ErrorAction SilentlyContinue
        Start-Sleep -Seconds 5
    } while ($service.Status -ne 'Running' -and ([datetime]::Now - $startTime).TotalSeconds -lt $TimeoutSeconds)

    if ($service.Status -eq 'Running') {
        Write-Output "The 'loginagent' service on $ComputerName has started successfully."
        return $true
    } else {
        Write-Output "Failed to verify that the 'loginagent' service is running on $ComputerName."
        return $false
    }
}