Scheduled Task Set ADR Disabled or Enabled SCCM ConfigMgr

When I setup a customers SCCM (ConfigMgr) site for patching I use ADR’s (Automatic Deployment Rules) to create a no hassle patching cycle each month.
This is done by automatically creating the monthly Software Update groups and then creating the deployments but NOT enabling them to the customer’s Pilot collections, Release Collections and Production Collections. This allows the customer to effectively “right click, enable” the deployment to that collection when ready.

The problem you have with this is the “Critical” security patches that are released out of the usual time period. You know the patches that cover that hole that no one noticed before release!
Anyway to get round that I create more ADR’s that run every day checking for a “Critical” Patch release. The issue with this is if left… Yep you guessed it, it will run on the monthly schedule day as well, which will just duplicate content.

So I came up with this Script to be run as a Scheduled Task by a service account just before the main ADR’s run and then later that day when they are complete.

Here is the Script:

##############################################################################################################################################
#Author: C5 Richie Schuster - SCCMOG.COM
#Script: Set-ADREnableDisabled
#Usage : "Set-ADREnableDisabled -State Enabled -SiteCode S0G" or "Set-ADREnableDisabled -State Disabled -SiteCode S0G"
#Info  : This script was writtent to run as a scheduled task to automatically disable and enable ADR Rules specified in the variable $ADRNames
##############################################################################################################################################
#Parameters
Param
(
[parameter(mandatory=$true,HelpMessage="Please, provide your SiteCode.")][ValidateNotNullOrEmpty()][String]$SiteCode = "",
[parameter(mandatory=$true,HelpMessage="Please, provide a state for the script to Run e.g. Enable or Disable")][ValidateNotNullOrEmpty()][String]$State = ""
)

#ADR Names stored in ARRAY -  Copy and Pasted name of ADR Bellow.
$ADRNames = @("ADR Critical Security Releases Windows 10 1607",`
            "ADR Critical Security Releases Windows 10 1511")

#Disable warnings for Fast switch
$CMPSSuppressFastNotUsedCheck = $true

# Check for elevation
Write-Host "Checking for elevation"
If (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
    [Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    Write-Warning "Oupps, you need to run this script from an elevated PowerShell prompt!`nPlease start the PowerShell prompt as an Administrator and re-run the script."
    Write-Warning "Aborting script..."
    Break
}
#Import Module but check if user entered sitecode
If ($SiteCode -ne "") {
#[string]$SiteCode = "P01"
# Import the ConfigurationManager.psd1 module 
Write-Host "Importing ConfigMgr Module..." -ForegroundColor Yellow
Import-Module "$($ENV:SMS_ADMIN_UI_PATH)\..\ConfigurationManager.psd1"
# Set the current location to be the site code.
Write-Host "Setting Location to ConfigMgr Drive..." -ForegroundColor Yellow
Set-Location "$SiteCode`:"
}
Else {
    Write-Warning "Oupps, you need to enter a Site code!`nPlease use the -SiteCode followed by your sitecode."
    Write-Warning "Aborting script..."
    Break
}

#If State set to Disable
If ($State -eq "Disable") {
    Foreach ($ADR in $ADRNames) {
        #Retrieve ADR information
        $RetADR = Get-CMSoftwareUpdateAutoDeploymentRule -Name $ADR
            #Check if ADR is Enabled and if so disable
            If ($RetADR.AutoDeploymentEnabled -eq $True) {
                Write-Host "Its On... Disabling...." -ForegroundColor Yellow
                #Disable ADR
                Set-CMSoftwareUpdateAutoDeploymentRule -Name $RetADR.Name -Enable $false
                #Check Action successfully completed.
                $Check = Get-CMSoftwareUpdateAutoDeploymentRule -Name $ADR
                If ($Check.AutoDeploymentEnabled -eq $False) {
                    Write-Host "Successfully Disabled $($Check.Name)!" -ForegroundColor Green
                    }
            }
            #If ADR Already Enabled Warn User and move onto next.
            ElseIf ($RetADR.AutoDeploymentEnabled -eq $false) {
                    Write-Host "$($Check.Name) is already disabled!" -ForegroundColor Green
            }
            #If ADR same as previous name or not pupulated then warn user.
            Elseif (($RetADR.Name -ne $ADR) -or ($RetADR -eq $null)) {
                    Write-Host "ADR $ADR cannot be found!" -ForegroundColor Red        
            }
            #If you hit this something fishy is going on!
            Else {
                Write-Host "Error please message Richie Schuster C5 - SCCMOG.com" -ForegroundColor Red 
            }
    }
}

#If State set to Enable
ElseIf ($State -eq "Enable") {
    Foreach ($ADR in $ADRNames) {
        #Retrieve ADR information
        $RetADR = Get-CMSoftwareUpdateAutoDeploymentRule -Name $ADR
            #Check if ADR is Disabled and if so enable
            If ($RetADR.AutoDeploymentEnabled -eq $False) {
                Write-Host "Its Off... Enabling...." -ForegroundColor Yellow
                #Enable ADR
                Set-CMSoftwareUpdateAutoDeploymentRule -Name $RetADR.Name -Enable $True
                #Check Action successfully completed.
                $Check = Get-CMSoftwareUpdateAutoDeploymentRule -Name $ADR
                If ($Check.AutoDeploymentEnabled -eq $True) {
                    Write-Host "Successfully Enabled $($Check.Name)!" -ForegroundColor Green
                    }
            }
            #If ADR Already Disabled Warn User and move onto next.
            ElseIf ($RetADR.AutoDeploymentEnabled -eq $True) {
                    Write-Host "$($Check.Name) is already enabled!" -ForegroundColor Green
            }
            #If ADR same as previous name or not pupulated then warn user.
            Elseif (($RetADR.Name -ne $ADR) -or ($RetADR -eq $null)) {
                    Write-Host "ADR $ADR cannot be found!" -ForegroundColor Red        
            }
            #If you hit this something fishy is going on!
            Else {
                Write-Host "Error please message Richie Schuster C5 - SCCMOG.com" -ForegroundColor Red 
            }
    }
}
#If Input empty or does not match write warning.
Else {
    Write-Host "Please use Enable or Disable param e.g. Set-ADREnableDisabled -State Enable  -SiteCode S0G" -ForegroundColor Red
    Set-Location $PSScriptRoot
}
################################################################

Here is the XML for the Scheduled Task to disable the daily ADRs. You will have to change some details but this should get you going. When you want to re-enable it in the evening just change line 65 from Disable to enable:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2017-05-02T16:06:29.8383361</Date>
    <Author>SCCMOG\Administrator</Author>
    <Description>This task runs one a month to disable the critical security ADRs.</Description>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2017-05-02T01:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByMonthDayOfWeek>
        <Weeks>
          <Week>2</Week>
        </Weeks>
        <DaysOfWeek>
          <Wednesday />
        </DaysOfWeek>
        <Months>
          <January />
          <February />
          <March />
          <April />
          <May />
          <June />
          <July />
          <August />
          <September />
          <October />
          <November />
          <December />
        </Months>
      </ScheduleByMonthDayOfWeek>
    </CalendarTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>YourDomain\SCCMAdmin</UserId>
      <LogonType>Password</LogonType>
      <RunLevel>HighestAvailable</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>Powershell.exe</Command>
      <Arguments>-ExecutionPolicy Bypass -File D:\Setup\Scripts\Set-ADREnableDisabled.ps1 .\Set-ADREnableDisabled.ps1 -State Disable -SiteCode P01</Arguments>
    </Exec>
  </Actions>
</Task>

Leave a Reply

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

Copyright 2016 SCCMOG | All Rights Reserved

css.php