For this article we’ll walk through connecting to a random Exchange server in an environment to run a script. Why would we want to do this? Perhaps a pseudo load balance or just to keep the script from connecting to the same server all the time. So how would we do this? First, we need a list of Exchange Servers in an environment.
Option 1 (From a server with Exchange PowerShell module available and Array setup)
$ExchangeServers = @() $ExchangeServers = (Get-ExchangeServer).Name
Option 2 (Regular server with AD PS Module installed:
Import-Module ActiveDirectory $ExchangeServers = (Get-ADGroupMember 'Exchange Servers' | Where {$_.Name -ne 'Exchange Install Domain Servers'}).Name
Next we need a total count for the servers, which will serve as the largest number in a random array:
$ServerCount = $ExchangeServers.Count
Now, we need a random number from 0 to the max number of servers ($ServerCount)
$Random = Get-Random -Min 0 -Max ($ServerCount-1)
After we have this, we can connect to Exchange:
$DNSRoot = (Get-ADDomain).DNSRoot $ServerFQDN = $ExchangeServers[$Random]+'.'+$DNSRoot $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$ServerFQDN/PowerShell/ -Authentication Kerberos Import-PSSession $Session -DisableNameChecking
Maybe a bit long, but it will provide a randomness to your PowerShell connections.
Better code? Shorter? More complex?! Feel free to leave a comment. Would love to heard from my readers on this. Heck, maybe you think this is a silly waste of PowerShell. Leave a comment!