Sample #PowerShell code for my TechEd Session – Demo 2 – Create Collections and Maintenance Windows for Server Patching.

Here’s an example of creating collections (with maintenance windows) for server patching.

Start with a .csv of servers, and the desired patch window (download sample csv).

You then run the PowerShell script to group the systems and populate new collections.
Download Script…

(if you’re having trouble with copy/paste of the code, or if code doesn’t look correct (with line feed, etc), please try an alternate browser. . .:( )


#Demo 2 - Software Update Scenario
$CMModulePath = $Env:SMS_ADMIN_UI_PATH.ToString().SubString(0,$Env:SMS_ADMIN_UI_PATH.Length - 5) `
    + "\ConfigurationManager.psd1"
Import-Module $CMModulePath -force
cd PR1:

#Removing Old Collections that begin with 'Serverpatch'
Get-CMDeviceCollection| Where-Object {$_.name -like "serverpatch*"} | Remove-CMDeviceCollection -force

#import the csv of servers with patch window
$Servers = import-csv C:\scripts\ServerPatchWindows.csv

#use the group-object cmdlet to group servers into patch windows
$Servers | Group-Object Patchwindow | ForEach-Object {
    #Gives us a window name like ServerPatch_5_26_2014_20_00
    $PatchWindowName = "ServerPatch_" + $_.Name -replace "[:\./ ]", "_"
    $PatchWindowName  

    "Creating Collection {0}" -f $PatchWindowName
    $NewColl = New-CMDeviceCollection -Name $PatchWindowName -LimitingCollectionName "All Servers" 

    #Create Schedule for 5 hour MW
    $Schedule = New-CMSchedule -Nonrecurring  -Start ([datetime]$_.Name) -durationinterval Hours -DurationCount 5

    #Create MW
    New-CMMaintenanceWindow -Name ("Maint" + $PatchWindowName) -ApplyToSoftwareUpdateOnly `
        -CollectionID $NewColl.CollectionID -Schedule $Schedule
    $Schedule = $null

    #Create Server list separated by commas
    $_.Group | foreach {
       $string = $string + '"' + $_.Servername + '",'
    }

    #build the WQL and remove the extra comma
    $wql = "select *  from  SMS_R_System where SMS_R_System.Name in (" + $string.trimend(',') + ")"
    Add-CMDeviceCollectionQueryMembershipRule -CollectionId $NewColl.CollectionID `
        -RuleName "Query1" -QueryExpression $wql
    $string = $null
}

Download Script…

Happy Scripting!

Greg

This post first appeared on http://www.gregramsey.net