Private/Get-RandomPingableServer.ps1
<#
.SYNOPSIS Returns a randomly selected server from a list that responds to a ping test. .DESCRIPTION The Get-RandomPingableServer function takes an array of server names and iteratively selects one at random, checking if it is reachable using `Test-Connection`. It returns the first server that is pingable. If no server is reachable, it returns `$null` and logs a message. .PARAMETER ServerList An array of server names (FQDNs or NetBIOS names) to test for availability via ICMP ping. .EXAMPLE $servers = @("server01", "server02", "server03") $pingableServer = Get-RandomPingableServer -ServerList $servers Returns one of the servers that successfully responds to a ping. .NOTES - This function stops as soon as a pingable server is found. - Requires the `Write-LogEntry` helper function to log output. - Useful for picking an available server from a pool for failover, load balancing, or backup execution. #> function Get-RandomPingableServer { [CmdletBinding()] param ( [Parameter(Mandatory = $true)] [string[]]$ServerList ) $triedServers = @() while ($triedServers.Count -lt $ServerList.Count) { # Pick a random server that hasn't been tried $remainingServers = $ServerList | Where-Object { $_ -notin $triedServers } $randomServer = Get-Random -InputObject $remainingServers $triedServers += $randomServer # Try pinging the server if (Test-Connection -ComputerName $randomServer -Count 1 -Quiet -ErrorAction SilentlyContinue) { Write-LogEntry -Message "Pingable Server: $randomServer" return $randomServer } } Write-LogEntry -Message "No pingable servers found." return $null } |