Public/Get-AvailableServer.ps1
<#
.SYNOPSIS Retrieves the first available server from a list by testing connectivity. .DESCRIPTION This function takes a list of server names, pings each server, and returns the first server that responds successfully. The servers are tested in a randomized order. .PARAMETER Servers An array of server names to be tested for availability. .PARAMETER PingCount The number of ICMP echo requests to send to each server. Default is 1. .OUTPUTS System.String The name of the first available server that responds to the ping. .EXAMPLE $servers = @("Server1", "Server2", "Server3") $availableServer = Get-AvailableServer -Servers $servers Write-Output "Available server: $availableServer" .EXAMPLE $servers = @("Server1", "Server2", "Server3") $availableServer = Get-AvailableServer -Servers $servers -PingCount 3 Write-Output "Available server: $availableServer" #> function Get-AvailableServer { param ( [Parameter(Mandatory = $true)] [string[]]$Servers, [int]$PingCount = 1 ) # Randomize the list of Servers $shuffledServers = $Servers | Get-Random -Count $Servers.Count foreach ($Server in $shuffledServers) { try { $pingResult = Test-Connection -ComputerName $Server -Count $PingCount -Quiet if ($pingResult) { return $Server } } catch { Write-Warning "Error pinging $Server : $_" } } return $null } |