Public/Invoke-RPAReboot.ps1


<#
.SYNOPSIS
    Initiates a reboot of a specified host and verifies its operational status afterward.
 
.DESCRIPTION
    This function reboots the server if no users are logged on. Post-reboot, it confirms if a specified service is running on the system.
 
.PARAMETER HostName
    The name of the host to reboot.
 
.PARAMETER ServiceName
    The service to check for operational status post-reboot.
 
.EXAMPLE
    Invoke-RPAReboot -HostName "Server01" -ServiceName "loginagent"
    Attempts to reboot "Server01" and checks if the "loginagent" service is running post-reboot.
 
.NOTES
    The function checks for user logoff before initiating a reboot. It requires network access and administrative privileges on the target host.
#>


Function Invoke-RPAReboot {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$HostName,

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

    if (Test-Connection -ComputerName $HostName -Count 2 -Quiet) {
        $status = Get-LoggedInStatus -ComputerName $HostName

        if ($status -eq 'Not logged on.') {
            Write-Output "Please wait while we reboot the server $HostName."
            try {
                if ((Get-WmiObject Win32_OperatingSystem -ComputerName $HostName | Invoke-WmiMethod -Name Win32Shutdown -ArgumentList 6).ReturnValue -eq 0) {
                    Start-Sleep -Seconds 15
                    if (Check-SystemState -ComputerName $HostName -ServiceName $ServiceName) {
                        Write-Output "$(Get-Date) - $HostName Successfully Restarted"
                    } else {
                        Write-Output "Failed to verify restart on $HostName."
                    }
                } else {
                    Write-Output "Failed to initiate reboot on $HostName."
                }
            } catch {
                Write-Output "Error during reboot process: $_"
            }
        } elseif ($status -eq 'Computer in use.') {
            $userDetails = Get-WmiObject -Class Win32_ComputerSystem -ComputerName $HostName -ErrorAction Stop
            Write-Output "$($userDetails.UserName) is logged in already on $HostName. Please log off the user before retrying."
        }
    } else {
        Write-Output "$HostName is not reachable."
    }
}