Tuesday 3 February 2015

Don’t let a offline exchange server affect your scripts!!!

I’m sure you like most of you have being remote power shelling for some time but if you are running an on prem solution this might be worth adding to your scripts. In short a simple loop based on a static array. 

Such a loop will assist with completing a retry in the event that the remote session is unable to be created to the exchange server.  

$ExchangeServers = ("SRVEXC001","SRVEXC002")
$SessionActive = $false
$Counterlimit = 10
$Counter = 0

DO

{
       Try{
    $ExchangeServersSession = $ExchangeServers | Get-Random
    Write-Warning "Attempting to Connect to Exchange Server: $ExchangeServersSession"
       $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$ExchangeServersSession/PowerShell/ -Authentication Kerberos -ErrorAction SilentlyContinue
    $Counter++
    $SessionCurrent = Get-PSSession | Where{($_.ConfigurationName -eq 'Microsoft.Exchange') -and ($_.State -eq 'Opened') -and ($_.Availability -eq 'Available')}

    }

    Catch{
   
    }

    Finally{
    If($SessionCurrent){Write-Warning "Connected to Exchange Server: $ExchangeServersSession";Import-PSSession $Session;$error.clear();$SessionActive = $true}

    }
} Until (($SessionActive -eq $true) -or ($Counter -gt $Counterlimit))     


If($Counter -gt $Counterlimit){Write-error "No Exchange Servers are responding to Remote Powershell Requests"


You could also automate the static array $ExchangeServers and select the servers you require without too much hassle but I’ll let you guys look after that part… J

No comments:

Post a Comment