PowerShell problems when setting failover SCOM Management Servers

I have recently been writing a couple of System Center Operations Manager maintenance scripts to configure failover and came across a PowerShell issue that I had not realised before.

The script I was to loop through all of the agents reporting to one of my management servers and set the secondary management server to the failover pair. This script was as follows:

$PrimaryMS = Get-SCOMManagementServer -Name jon-scom03-01.jonathan.local

$SecondaryMS = Get-SCOMManagementServer -Name jon-scom03-02.jonathan.local

$Agents = Get-SCOMAgent -ManagementServer $PrimaryMS

foreach ($Agent in $Agents)

{

   Set-SCOMParentManagementServer -Agent $Agent -FailoverServer $SecondaryMS

}

 

The problem that I had was that the command was failing because it was trying to run for a null agent. This meant that PowerShell was executing the Set-SCOMParentManagementServer command, even when there were no agents – which do not seem right to me.

However, on investigation, I discovered that this was a known problem and was due to the fact that I was returning the list of agents into a variable. Because this variable had to contain something, it contains the value $Null. When I then run the foreach command, it finds that there is a single entry in the array (i.e. $Null) and therefore executes the contents on that.

I found that there were two solutions for this

Option 1 (Check for null):

$Agents = Get-SCOMAgent -ManagementServer $PrimaryMS

foreach ($Agent in $Agents)

{

   If ($Agent –ne $Null) {Set-SCOMParentManagementServer -Agent $Agent -FailoverServer $SecondaryMS}

}

 

Option 2 (use a pipeline):

Get-SCOMAgent -ManagementServer $PrimaryMS | foreach

{

  Set-SCOMParentManagementServer -Agent $_ -FailoverServer $SecondaryMS

}

 

Both of these worked in my testing, but I felt that Option 1 was the clearest for people to read when they came to review the code at a later date. Personally I would like to see a switch on the foreach command so you could tell it to ignore $null arrays, but in the meantime this work around will get your scripts doing what they are meant to. It also leads to a bit of good practice when it comes to script writing – always make sure you test that they will run correctly when there is nothing for them to do!

Enterprise Mobility Workshops - 24th November 2015 - London | 9:00am – 3:00pm

Leave a Reply

Your email address will not be published. Required fields are marked *