| <# | |
| This program is free software: you can redistribute it and/or modify | |
| it under the terms of the GNU General Public License as published by | |
| the Free Software Foundation, either version 3 of the License, or | |
| (at your option) any later version. | |
| This program is distributed in the hope that it will be useful, | |
| but WITHOUT ANY WARRANTY; without even the implied warranty of | |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
| GNU General Public License for more details. | |
| You should have received a copy of the GNU General Public License | |
| along with this program. If not, see <https://www.gnu.org/licenses/>. | |
| #> | |
| <# | |
| .SYNOPSIS | |
| Maintain Software Updates in System Center Configuration Manager. | |
| .DESCRIPTION | |
| This script can be used to perform numerous software update maintenance tasks. It can be used to decline updates based on supersedence, title, or external plugins. By declining updates you remove them from the catalog that clients scan against. This reduces the amount of resources required by the server to generate the catalog and for the client to perform the scan. In extreme cases this can be the difference between failure and success. The script can also remove the declined updates and any expired updates from all Software Update Groups. Lastly, the script can also remove any unneeded updates from the deployment package source folders. It's recommended to first run the script with the -WhatIf switch to determine the impact of running the script. | |
| .EXAMPLE | |
| Powershell -File .\Invoke-DGASoftwareUpdateMaintenance.ps1 -FirstRun -Force | |
| Call the WSUS database's internal stored procedures to delete obsolete updates. Use this to do the initial cleanup in environments that have never been maintained. | |
| .EXAMPLE | |
| Powershell -File .\Invoke-DGASoftwareUpdateMaintenance.ps1 -RunCleanUpWizard -Force | |
| Run WSUS cleanup wizard. If the script has been ran in the last 24 hours force it to run anyways. | |
| .EXAMPLE | |
| Powershell -File .\Invoke-DGASoftwareUpdateMaintenance.ps1 -DeclineSuperseded -UpdateListOutputFile OutFile.csv | |
| Decline all superseded updates older than the period defined in the site's software update component. Output a list of declined updates to OutFile.csv. | |
| .EXAMPLE | |
| Powershell -File .\Invoke-DGASoftwareUpdateMaintenance.ps1 -DeclineSuperseded -DeclineLastLevelOnly | |
| Decline all superseded updates older than the period defined in the site's software update component and do not supersede other updates. | |
| .EXAMPLE | |
| Powershell -File .\Invoke-DGASoftwareUpdateMaintenance.ps1 -DeclineSuperseded -ExclusionPeriod 6 | |
| Decline all superseded updates older than 6 months. | |
| .EXAMPLE | |
| Powershell -Command "& '.\Invoke-DGASoftwareUpdateMaintenance.ps1' -DeclineByTitle @('*Itanium*','*ia64*','*Beta*')" | |
| Decline all updates whose titles include the words 'Itanium', 'ia64', or 'Beta'. | |
| .EXAMPLE | |
| Powershell -Command "& '.\Invoke-DGASoftwareUpdateMaintenance.ps1' -CleanSUGs -RemoveEmptySUGs" | |
| Remove declined and expired updates from all software update groups and delete remove any empty software update groups. | |
| .EXAMPLE | |
| Powershell -Command "& '.\Invoke-DGASoftwareUpdateMaintenance.ps1' -CombineSUGs 3 -CleanSources" | |
| Combine and remove ADR generated software updates groups where more than three exist and remove unnecessary updates from the deployment package source files. | |
| .EXAMPLE | |
| Powershell -Command "& '.\Invoke-DGASoftwareUpdateMaintenance.ps1' -UpdateADRDeploymentPackages Monthly" | |
| Verify that each automatic deployment is using a deployment package for the current month. If the package does not exist then create it. | |
| .EXAMPLE | |
| Powershell -Command "& '.\Invoke-DGASoftwareUpdateMaintenance.ps1' -MaxUpdateRuntime @{'*Security Monthly Quality Rollup For Windows*'=60;'*Security and Quality Rollup for .NET*'=120}" | |
| Set the maximum runtime to 60 minutes for Windows cumulative rollups and 120 minutes for the .NET cumulative rollups. | |
| .EXAMPLE | |
| Powershell -ExecutionPolicy bypass -Command "& '.\Invoke-DGASoftwareUpdateMaintenance.ps1' -DeclineSuperseded -DeclineByTitle @('*Itanium*','*ia64*','*Beta*') -DeclineByPlugins -ReSyncUpdates -CleanSUGs -RemoveEmptySUGs -CombineSUGs 3 -UpdateADRDeploymentPackages Yearly -MaxUpdateRuntime @{'*Security Monthly Quality Rollup For Windows*'=60;'*Security and Quality Rollup for .NET*'=30}" -CleanSources" | |
| Run WSUS cleanup wizard and decline all superseded updates older than the period defined in the site's software update component, all updates whose titles include the words 'Itanium', 'ia64', or 'Beta', and updates based on external plugin files. Then initiate an update synchronization, remove declined and expired updates from all software update groups, remove any empty software update groups, combine and remove software updates groups generated by automatic deployment rules where more than three exist, verify that the automatic deployment rules are using the correct yearly deployment package, set the maximum runtime to 60 minutes for Windows cumulative rollups and 30 minutes for the .NET cumulative rollups, and remove unnecessary updates from the deployment package source files. | |
| .EXAMPLE | |
| Powershell -File .\Invoke-DGASoftwareUpdateMaintenance.ps1 -StandAloneWSUS WSUSSever.domain.com -DeclineSuperseded -DeclineByTitle @('*Itanium*','*ia64*','*Beta*') -DeclineByPlugins" | |
| Run script against a stand-alone WSUS server and running the cleanup wizard and declining all superseded updates older than the period defined in the site's software update component, all updates whose titles include the words 'Itanium', 'ia64', or 'Beta', and updates based on external plugin files. | |
| .NOTES | |
| The script will create an empty text file in the root of its folder to track the last time it was ran and will not run if this file is newer than 24 hours old. Use the -Force parameter to override. | |
| The DeclineByTitle parameter takes an array of strings and the MaximumUpdateRuntime takes a hashtable. While the script has logic to try and interpret normal strings as both types it is recommended that you call the program using the -Command option when using these parameters so that you can pass the proper object type. | |
| When using the MaximumUpdateRuntime parameter note that when Configuration Manager syncs updates that it will revert to the default value if it is higher than your custom setting. | |
| Written By: Bryan Dam | |
| Version 1.1: 10/15/17 | |
| Version 1.2: 10/17/17 | |
| Version 1.3: 10/20/17 | |
| Version 1.4: 10/23/17 | |
| Version 1.5: 10/28/17 | |
| Version 1.6: 11/05/17 | |
| Version 1.7: 03/02/18 | |
| Version 1.8: 04/09/18 Renamed the MaxiumumUpateRuntime to MaxUdateRuntime b/c I'm a dumbass that can't spell | |
| Version 1.9: 04/09/18 Renamed MaxUdateRuntime to MaxUpdateRuntime, removed .Where calls for PoSH 3 compatibility, added SiteCode parameter to cmdlets that support it for multi-site environments | |
| Version 2.0: 04/16/18 | |
| Added FirstRun parameter used to try and get past timeouts in environments that have not been maintained. | |
| Fixed issues with CleanSources routine. | |
| Added/fixed pretty progress bars when running interactively. | |
| Make ExclusionPeriod nullable so that null can be detected and zero can be passed properly. | |
| Added support for running against a stand-alone WSUS server. | |
| Version 2.2 04/09/18 | |
| Fixed issue formatting the percent figure for progress bars. | |
| Version 2.3 06/25/18 | |
| Fixed my merge screw up that reverted to an earlier version that did not have the stand-alone WSUS feature. | |
| Using WhatIf will force the script to run regardless of the 24-hour timeout. | |
| Make DeclineByTitle explicitly case-insensitive. | |
| Version 2.4 10/17/18 | |
| In WhatIf mode don't check sync status when declining updates for performance reasons. | |
| In WhatIf mode don't write the last ran file. | |
| Added ExcludeByTitle, ExcludeByProduct, and IncludeByProduct options. | |
| Fixed some issues when running from the PowerShell ISE (Chad Simmons). | |
| Updated Windows 10 plugins to support the Win7/8.1 in place upgrades updates. | |
| Updated Windows 10 edition plugin to support the business and consumer in place upgrades. | |
| Created plugins to decline Itanium and 32-bit updates (Chad Simmons). | |
| Created plugin for Win7/8.1 in place upgrades updates. | |
| Support dynamic config file (see example). | |
| Created plugin that declines 32-bit updates except for Windows Server 2008 (non-R2). | |
| Support relative and default paths for config and output files. | |
| Added a new parameter called UseCustomIndexes which will create custom indexes to the WSUS database that increases performance and helps fix Cleanup Wizard timeouts. | |
| Added a new parameter called RemoveCustomIndexes which will remove the custom indexes. | |
| Delete declined updates older than twice the Exclusion period using WSUS API. | |
| FirstRun: Increase timeout to 24 hours and try to get titles for obsolete updates. | |
| Version 2.4.1 | |
| Fix an issue with handling config file parameters (Chad Simmons) | |
| Uploaded the correct plugins this time. Maybe. | |
| Version 2.4.2 | |
| Fix another issue with handling config file parameters (Chad Simmons) | |
| Added license information. | |
| Version 2.4.3 | |
| Fix config_wsus_standalone configuration file. | |
| Remove check for WSUS cmdlets to support Server 2008 R2 (sigh ... for real people?!) | |
| Version 2.4.4 01/06/19 | |
| Moved Get-WSUSDB into the features that need it to avoid DB connection issues where a DB isn't needed anyways. | |
| Version 2.4.5 01/19/19 | |
| Fix the count of declined superseded updates. | |
| Fix WhatIf handling for UpdateADRDeploymentPackages. | |
| Version 2.4.6 12/19/2019 | |
| Improved some WhatIf handling. | |
| Added catalog size information. | |
| Version 2.4.7 01/08/20 | |
| The sync check will now check for multiple status messages to determine if the SUP is still syncing. (Charles - @NoRemoteUsers). | |
| Version 2.4.8 01/24/20 | |
| Change Get-CatalogInfo function to make its own connection. | |
| Fix Boolean handling in settings file. | |
| [TODO] Sync approvals throughout hierarchy. | |
| [TODO] Orchestrate decline top-down and cleanup bottom-up throughout hierarchy. | |
| Version 2.4.9 09/17/20 | |
| Internal code updates for Set-Location/Pop-Location, spelling, spacing, aliases/full cmdlets, etc. | |
| Add config file for datFile | |
| Update config file processing to better detect UNC and file paths | |
| Add scriptFile variable and set default config files to be scriptFile.<associated extension> | |
| Updated logging to prepend WhatIf when running in WhatIf mode | |
| Archive last output file | |
| Update O365 plugin with new channel names [Damien Solodow] | |
| Add several plugins [Chad Simmons, Damien Solodow] | |
| Fix the lookup for ConfigMgr supersedence settings. | |
| Version 2.5.0 09/17/20 | |
| Fixed the fix for looking up ConfigMgr supersedence settings. | |
| Version 2.5.1 09/19/20 | |
| Fixed the fix for the fix for looking up ConfigMgr supersedence settings. | |
| Version 2.5.2 11/04/22 | |
| If in WhatIf mode, make $AllUpdates a global variable so it can be used after the script exits. | |
| .LINK | |
| http://www.damgoodadmin.com | |
| #> | |
| [CmdletBinding(SupportsShouldProcess=$True,DefaultParameterSetName="configfile")] | |
| Param( | |
| #Connect to the WSUS database directly and use the built in stored procedures to delete obsolete updates. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $FirstRun, | |
| #Add custom indexes to the WSUS database. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $UseCustomIndexes, | |
| #Remove custom indexes to the WSUS database. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $RemoveCustomIndexes, | |
| #Delete declined updates. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $DeleteDeclined, | |
| #Decline superseded updates. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $DeclineSuperseded, | |
| #Only decline the last level of superseded updates which do not supersede any other updates. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $DeclineLastLevelOnly, | |
| #Only decline superseded updates that haven't been modified for the given number of months. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [System.Nullable[int]] $ExclusionPeriod, | |
| #Array of strings to search for and decline updates that match. Use wildcard operator (*) to match more than one update. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string[]] $DeclineByTitle, | |
| #Run powershell scripts in the plugin folder to select updates to decline. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch] $DeclineByPlugins, | |
| #Array of title strings that will be excluded and not declined. This exclusion will apply to all methods of selecting updates to decline. Use wildcard operator (*) to match more than one update. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string[]] $ExcludeByTitle, | |
| #Array of product strings that will be excluded and not declined. This exclusion will apply to all methods of selecting updates to decline. Use wildcard operator (*) to match more than one update. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string[]] $ExcludeByProduct, | |
| #Array of product strings that will be included and declined. This inclusion will apply to all methods of selecting updates to decline. Use wildcard operator (*) to match more than one update. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string[]] $IncludeByProduct, | |
| #Output the list of updates to this file. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string]$UpdateListOutputFile, | |
| #Run the WSUS cleanup wizard. This occurs after declining updates. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch]$RunCleanUpWizard, | |
| #Set the log file. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string]$LogFile, | |
| #The maximum size of the log in bytes. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [int]$MaxLogSize = 2621440, | |
| #The number of minutes to wait after the last sync to run the wizard. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [int]$SyncLeadTime = 5, | |
| #Force the script to run even if it was run recently. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [Parameter(ParameterSetName='configfile')] | |
| [switch]$Force, | |
| #After declining updates resync the update catalog to bring the changes into Configuration Manager. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch]$ReSyncUpdates, | |
| #When declining an update also remove it from all software update groups. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch]$CleanSUGs, | |
| #If a software update group is left empty, remove it. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch]$RemoveEmptySUGs, | |
| #Combine software updates groups into yearly groups leaving only the provided number of groups. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [Parameter( HelpMessage="A number greater than zero.")] | |
| [ValidateScript({$_ -gt 0})] | |
| [int]$CombineSUGs, | |
| #A list of update title searches and the maximum runtime to set those updates to. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [Alias("MaxiumumUpateRuntime ")] | |
| $MaxUpdateRuntime, | |
| #Clean up any source files that are no longer associated to an active deployment. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [switch]$CleanSources, | |
| #Updates the distribution packages used by ADRs. | |
| [Parameter( ParameterSetName='cmdline',HelpMessage="You must select either Yearly or Monthly distribution packages for the automatic deployment rules.")] | |
| [ValidateSet("Yearly","Monthly")] | |
| [string]$UpdateADRDeploymentPackages, | |
| #Define the sitecode. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string][ValidateLength(3,3)]$SiteCode, | |
| #Define a standalone WSUS server. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [string]$StandAloneWSUS, | |
| #Define the standalone WSUS server port. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [int]$StandAloneWSUSPort, | |
| #Define the standalone WSUS server's SSL setting. | |
| [Parameter(ParameterSetName='cmdline')] | |
| [bool]$StandAloneWSUSSSL = $False, | |
| #Define a configuration file. | |
| [Parameter(ParameterSetName='configfile')] | |
| [string]$ConfigFile | |
| ) | |
| #region Functions | |
| Function Add-TextToCMLog { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Log to a file in a format that can be read by Trace32.exe / CMTrace.exe | |
| .DESCRIPTION | |
| Write a line of data to a script log file in a format that can be parsed by Trace32.exe / CMTrace.exe | |
| The severity of the logged line can be set as: | |
| 1 - Information | |
| 2 - Warning | |
| 3 - Error | |
| Warnings will be highlighted in yellow. Errors are highlighted in red. | |
| The tools to view the log: | |
| SMS Trace - http://www.microsoft.com/en-us/download/details.aspx?id=18153 | |
| CM Trace - Installation directory on Configuration Manager 2012 Site Server - <Install Directory>\tools\ | |
| .EXAMPLE | |
| Add-TextToCMLog c:\output\update.log "Application of MS15-031 failed" Apply_Patch 3 | |
| This will write a line to the update.log file in c:\output stating that "Application of MS15-031 failed". | |
| The source component will be Apply_Patch and the line will be highlighted in red as it is an error | |
| (severity - 3). | |
| #> | |
| ########################################################################################################## | |
| #Define and validate parameters | |
| [CmdletBinding()] | |
| Param( | |
| #Path to the log file | |
| [parameter(Mandatory=$True)] | |
| [String]$LogFile, | |
| #The information to log | |
| [parameter(Mandatory=$True)] | |
| [String]$Value, | |
| #The source of the error | |
| [parameter(Mandatory=$True)] | |
| [String]$Component, | |
| #The severity (1 - Information, 2- Warning, 3 - Error) | |
| [parameter(Mandatory=$True)] | |
| [ValidateRange(1,3)] | |
| [Single]$Severity | |
| ) | |
| #Obtain UTC offset | |
| $DateTime = New-Object -ComObject WbemScripting.SWbemDateTime | |
| $DateTime.SetVarDate($(Get-Date)) | |
| $UtcValue = $DateTime.Value | |
| $UtcOffset = $UtcValue.Substring(21, $UtcValue.Length - 21) | |
| #Create the line to be logged | |
| $LogLine = "<![LOG[$Value]LOG]!>" +` | |
| "<time=`"$(Get-Date -Format HH:mm:ss.fff)$($UtcOffset)`" " +` | |
| "date=`"$(Get-Date -Format M-d-yyyy)`" " +` | |
| "component=`"$Component`" " +` | |
| "context=`"$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name)`" " +` | |
| "type=`"$Severity`" " +` | |
| "thread=`"$($pid)`" " +` | |
| "file=`"`">" | |
| #Write the line to the passed log file | |
| Out-File -InputObject $LogLine -Append -NoClobber -Encoding Default -FilePath $LogFile -WhatIf:$False | |
| } | |
| ########################################################################################################## | |
| Function Get-CMSoftwareUpdateSyncStatus { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Returns the sync status for each software update point in the site. | |
| .NOTES | |
| This function is provided in 1706 so this is just a stop-gap until that version has reached critical mass. | |
| #> | |
| ########################################################################################################## | |
| $SyncStatus = Get-WmiObject -Namespace "ROOT\SMS\site_$($SiteCode)" -Query "Select * from SMS_SUPSyncStatus" | |
| $Results = @() | |
| #Create a new object to convert WMI's CIM_DATETIME to PowerShell DateTime | |
| ForEach ($status in $SyncStatus){ | |
| If ($status.LastReplicationLinkCheckTime){ $LastReplicationLinkCheckTime = [Management.ManagementDateTimeConverter]::ToDateTime($status.LastReplicationLinkCheckTime)} | |
| If ($status.LastSuccessfulSyncTime){ $LastSuccessfulSyncTime = [Management.ManagementDateTimeConverter]::ToDateTime($status.LastSuccessfulSyncTime)} | |
| If ($status.LastSyncStateTime){ $LastSyncStateTime = [Management.ManagementDateTimeConverter]::ToDateTime($status.LastSyncStateTime)} | |
| $properties = @{'LastReplicationLinkCheckTime'=$LastReplicationLinkCheckTime; | |
| 'LastSuccessfulSyncTime'=$LastSuccessfulSyncTime; | |
| 'LastSyncErrorCode'=$status.LastSyncErrorCode; | |
| 'LastSyncState'=$status.LastSyncState; | |
| 'LastSyncStateTime'=$LastSyncStateTime; | |
| 'ReplicationLinkStatus'=$status.ReplicationLinkStatus; | |
| 'SiteCode'=$status.SiteCode; | |
| 'SyncCatalogVersion'=$status.SyncCatalogVersion; | |
| 'WSUSServerName'=$status.WSUSServerName; | |
| 'WSUSSourceServer'=$status.WSUSSourceServer} | |
| $Results+= New-Object –TypeName PSObject –Prop $properties | |
| } | |
| Return $Results | |
| } | |
| ########################################################################################################## | |
| Function Invoke-CMSyncCheck { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Invoke a synchronization check on all software update points. | |
| .DESCRIPTION | |
| When ran this function will wait for the software update point synchronization process to complete | |
| successfully before continuing. | |
| .EXAMPLE | |
| Invoke-CMSyncCheck | |
| Check the ConfigMgr sync status with the default 5 minute lead time. | |
| #> | |
| ########################################################################################################## | |
| [CmdletBinding()] | |
| Param( | |
| [string] $LogFile = "Invoke-CMSyncCheck.log", | |
| #The number of minutes to wait after the last sync to run the wizard. | |
| [int]$SyncLeadTime = 5 | |
| ) | |
| $component = "Invoke-CMSyncCheck" | |
| $WaitInterval = 0 #Used to skip the initial wait cycle if it isn't necessary. | |
| Do{ | |
| #Wait until the loop has iterated once. | |
| If ($WaitInterval -gt 0){ | |
| Add-TextToCMLog $LogFile "Waiting $TimeToWait minutes for lead time to pass before executing." $component 1 | |
| Start-Sleep -Seconds ($WaitInterval) | |
| } | |
| #Loop through each SUP and wait until they are all done syncing. | |
| Do { | |
| #If synchronizing then wait. | |
| If($Synchronizing){ | |
| Add-TextToCMLog $LogFile "Waiting for software update points to stop syncing." $component 1 | |
| Start-Sleep -Seconds (300) | |
| } | |
| <# | |
| Source: http://eskonr.com/2015/01/download-sccm-configmgr-2012-r2-cu3-status-messages-documentation/ | |
| 6701 = WSUS Synchronization started. | |
| 6702 = WSUS Synchronization done. | |
| 6703 = WSUS Synchronization failed. | |
| 6704 = WSUS Synchronization in progress. Current phase: Synchronizing WSUS Server. | |
| 6705 = WSUS Synchronization in progress. Current phase: Synchronizing site database. | |
| 6706 = WSUS Synchronization in progress. Current phase: Synchronizing Internet facing WSUS Server. | |
| 6707 = Content of WSUS Server %1 is out of sync with upstream server %2. | |
| 6708 = WSUS synchronization complete, with pending license terms downloads. | |
| #> | |
| $SynchronizingStatusMessages = @(6701,6704,6705,6706) | |
| $Synchronizing = $False | |
| ForEach ($softwareUpdatePointSyncStatus in Get-CMSoftwareUpdateSyncStatus){ | |
| If($softwareUpdatePointSyncStatus.LastSyncState -in $SynchronizingStatusMessages){$Synchronizing = $True} | |
| } | |
| } Until(!$Synchronizing) | |
| #Loop through each SUP, calculate the last sync time, and make sure that they all synced successfully. | |
| $syncTimeStamp = Get-Date "1/1/2001 12:00 AM" | |
| ForEach ($softwareUpdatePointSyncStatus in Get-CMSoftwareUpdateSyncStatus){ | |
| If ($softwareUpdatePointSyncStatus.LastSyncErrorCode -ne 0){ | |
| Add-TextToCMLog $LogFile "The software update point $($softwareUpdatePointSyncStatus.WSUSServerName) failed its last synchronization with error code $($softwareUpdatePointSyncStatus.LastSyncErrorCode). Synchronize successfully before running $component." $component 2 | |
| Exit | |
| } | |
| If ($syncTimeStamp -lt $softwareUpdatePointSyncStatus.LastSyncStateTime) { | |
| $syncTimeStamp = $softwareUpdatePointSyncStatus.LastSyncStateTime | |
| } | |
| } | |
| #Calculate the remaining time to wait for the lead time to expire. | |
| if ($WhatIfPreference) { $TimeToWait = ($syncTimeStamp.AddMinutes($SyncLeadTime) - (Get-Date)).Minutes } | |
| else {$TimeToWait = 0} | |
| #Set the wait interval in seconds for subsequent loops. | |
| $WaitInterval = 300 | |
| } Until ($TimeToWait -le 0) | |
| Add-TextToCMLog $LogFile "Software update point synchronization states confirmed." $component 1 | |
| } | |
| ########################################################################################################## | |
| Function Invoke-WSUSSyncCheck { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Invoke a synchronization check on the passed in WSUS server. | |
| .DESCRIPTION | |
| When ran this function will wait for the WSUS synchronization process to complete | |
| successfully before continuing. | |
| .EXAMPLE | |
| Invoke-WSUSSyncCheck -WSUSServer $WSUSServer -SyncLeadTime 0 | |
| Check the WSUS server sync status with zero lead time. | |
| #> | |
| ########################################################################################################## | |
| [CmdletBinding()] | |
| Param( | |
| #A WSUS server object. | |
| [Parameter(Mandatory=$true)] | |
| [Microsoft.UpdateServices.Administration.IUpdateServer] $WSUSServer, | |
| [string] $LogFile = "Invoke-WSUSSyncCheck.log", | |
| #The number of minutes to wait after the last sync to run the wizard. | |
| [int]$SyncLeadTime = 5 | |
| ) | |
| $component = "Invoke-WSUSSyncCheck" | |
| #Get the WSUS subscription. | |
| Try{ | |
| $WSUSSubscription = $WSUSServer.GetSubscription() | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to get the subscription for the WSUS server to check the sync status." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Exit | |
| } | |
| If (!$WSUSSubscription) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to get the subscription for the WSUS server to check the sync status." $component 3 | |
| Exit | |
| } | |
| $WaitInterval = 0 #Used to skip the initial wait cycle if it isn't necessary. | |
| Do{ | |
| #Wait until the loop has iterated once. | |
| If ($WaitInterval -gt 0){ | |
| Add-TextToCMLog $LogFile "Waiting $TimeToWait minutes for lead time to pass before executing." $component 1 | |
| Start-Sleep -Seconds ($WaitInterval) | |
| } | |
| #If the WSUS server is synchronizing then wait for it to finish. | |
| Do { | |
| #If Synchronizing then wait. | |
| If($Synchronizing){ | |
| Add-TextToCMLog $LogFile "Waiting for WSUS server to stop syncing." $component 1 | |
| Start-Sleep -Seconds (300) | |
| } | |
| #Get the synchronization status. | |
| Try{ | |
| $Synchronizing = ($WSUSSubscription.GetSynchronizationStatus() -eq [Microsoft.UpdateServices.Administration.SynchronizationStatus]::Running) | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to get the synchronization status for the WSUS server." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Exit | |
| } | |
| } Until(!$Synchronizing) | |
| #Determine if the sync status was successful. | |
| Try{ | |
| $WSUSLastSyncInfo = $WSUSSubscription.GetLastSynchronizationInfo() | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to get the synchronization info for the WSUS server." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Exit | |
| } | |
| If(!$WSUSLastSyncInfo){ | |
| Add-TextToCMLog $LogFile "Failed to get the synchronization info for the WSUS server." $component 3 | |
| Exit | |
| } | |
| If ($WSUSLastSyncInfo.Result -eq [Microsoft.UpdateServices.Administration.SynchronizationResult]::Failed){ | |
| Add-TextToCMLog $LogFile "The WSUS server failed its last synchronization with error code $($WSUSLastSyncInfo.Error): $($WSUSLastSyncInfo.ErrorText)" $component 3 | |
| Add-TextToCMLog $LogFile "Synchronize successfully before running the script." $component 3 | |
| Exit | |
| } | |
| #Calculate the remaining time to wait for the lead time to expire. | |
| $TimeToWait = (($WSUSLastSyncInfo.EndTime).AddMinutes($SyncLeadTime) - ((Get-Date).ToUniversalTime())).Minutes | |
| #Set the wait interval in seconds for subsequent loops. | |
| $WaitInterval = 300 | |
| } Until ($TimeToWait -le 0) | |
| Add-TextToCMLog $LogFile "WSUS server synchronization state confirmed." $component 1 | |
| } | |
| ########################################################################################################## | |
| #Taken from https://stackoverflow.com/questions/5648931/test-if-registry-value-exists | |
| Function Test-RegistryValue { | |
| ########################################################################################################## | |
| <# | |
| .NOTES | |
| Taken from https://stackoverflow.com/questions/5648931/test-if-registry-value-exists | |
| #> | |
| Param( | |
| [Alias("PSPath")] | |
| [Parameter(Position = 0, Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)] | |
| [String]$Path, | |
| [Parameter(Position = 1, Mandatory = $true)] | |
| [String]$Value, | |
| [Switch]$PassThru | |
| ) | |
| Process { | |
| If (Test-Path $Path) { | |
| $Key = Get-Item -LiteralPath $Path | |
| If ($Key.GetValue($Value, $null) -ne $null) { | |
| If ($PassThru) { | |
| Get-ItemProperty $Path $Value | |
| } Else { | |
| $True | |
| } | |
| } Else { | |
| $False | |
| } | |
| } Else { | |
| $False | |
| } | |
| } | |
| } | |
| ########################################################################################################## | |
| Function Get-SiteCode { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Attempt to determine the current device's site code from the registry or PS drive. | |
| .DESCRIPTION | |
| When ran this function will look for the client's site. If not found it will look for a single PS drive. | |
| .EXAMPLE | |
| Get-SiteCode | |
| #> | |
| ########################################################################################################## | |
| #Try getting the site code from the client installed on this system. | |
| If (Test-RegistryValue -Path "HKLM:\SOFTWARE\Microsoft\SMS\Identification" -Value "Site Code"){ | |
| $SiteCode = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\SMS\Identification" | Select-Object -ExpandProperty "Site Code" | |
| } ElseIf (Test-RegistryValue -Path "HKLM:\SOFTWARE\Microsoft\SMS\Mobile Client" -Value "AssignedSiteCode") { | |
| $SiteCode = Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\SMS\Mobile Client" | Select-Object -ExpandProperty "AssignedSiteCode" | |
| } | |
| #If the client isn't installed try looking for the site code based on the PS drives. | |
| If (-Not ($SiteCode) ) { | |
| #See if a PSDrive exists with the CMSite provider | |
| $PSDrive = Get-PSDrive -PSProvider CMSite -ErrorAction SilentlyContinue | |
| #If PSDrive exists then get the site code from it. | |
| If ($PSDrive.Count -eq 1) { | |
| $SiteCode = $PSDrive.Name | |
| } | |
| } | |
| Return $SiteCode | |
| } | |
| ########################################################################################################## | |
| Function Confirm-StringArray { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Confirm that the string is not actually an array. | |
| .DESCRIPTION | |
| If a string array is passed with a single element containing commas then split the string into an array. | |
| #> | |
| ########################################################################################################## | |
| Param( | |
| [string[]] $StringArray | |
| ) | |
| If ($StringArray){ | |
| If ($StringArray.Count -eq 1){ | |
| If ($StringArray[0] -ilike '*,*'){ | |
| $StringArray = $StringArray[0].Split(",") | |
| Add-TextToCMLog $LogFile "The string array only had one element that contained commas. It has been split into $($StringArray.Count) separate elements." $component 2 | |
| } | |
| } | |
| } | |
| Return $StringArray | |
| } | |
| ########################################################################################################## | |
| Function Test-Exclusions { | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Determine if the update should be excluded or not. | |
| .DESCRIPTION | |
| Compare the update metadata against the exclusion filters and return true if the update should be | |
| excluded and return false if not. | |
| #> | |
| ########################################################################################################## | |
| Param( | |
| [Microsoft.UpdateServices.Administration.IUpdate] $Update | |
| ) | |
| #Exclusions by title. | |
| ForEach ($Title In $ExcludeByTitle){ | |
| If ($Update.Title -ilike $Title){Return $True} | |
| } | |
| #Exclusions by product. | |
| ForEach ($Product In $ExcludeByProduct){ | |
| If (($Update.ProductTitles -ilike $Product) -or ($Update.ProductFamilyTitles -ilike $Product)){Return $True} | |
| } | |
| #Inclusions by product. The product must be found. | |
| ForEach ($Product In $IncludeByProduct){ | |
| If (($Update.ProductTitles -inotlike $Product) -and ($Update.ProductFamilyTitles -inotlike $Product)){Return $True} | |
| } | |
| Return $False | |
| } | |
| ########################################################################################################## | |
| Function Get-WSUSDB{ | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Get the WSUS database configuration. | |
| .DESCRIPTION | |
| Use the WSUS api to get the database configuration and verify that you can successfully connect to the DB. | |
| #> | |
| ########################################################################################################## | |
| Param( | |
| [Parameter(Mandatory=$true)] | |
| [Microsoft.UpdateServices.Administration.IUpdateServer] $WSUSServer, | |
| [string] $LogFile ="Get-WSUSDB.log" | |
| ) | |
| $component = "Get-WSUSDB" | |
| Try{ | |
| $WSUSServerDB = $WSUSServer.GetDatabaseConfiguration() | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to get the WSUS database details from the active SUP." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Return | |
| } | |
| If (!($WSUSServerDB)){ | |
| Add-TextToCMLog $LogFile "Failed to get the WSUS database details from the active SUP." $component 3 | |
| Return | |
| } | |
| #This is a just a test built into the API, it's not actually making the connection we'll use. | |
| Try{ | |
| $WSUSServerDB.ConnectToDatabase() | |
| Add-TextToCMLog $LogFile "Successfully tested the connection to the ($($WSUSServerDB.DatabaseName)) database on $($WSUSServerDB.ServerName)." $component 1 | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to connect to the ($($WSUSServerDB.DatabaseName)) database on $($WSUSServerDB.ServerName)." $component 3 | |
| Add-TextToCMLog $LogFile "Error ($($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Return | |
| } | |
| Return $WSUSServerDB | |
| } | |
| Function Connect-WSUSDB{ | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Connect to the WSUS database. | |
| .DESCRIPTION | |
| Use the database configuration to connect to the DB. | |
| #> | |
| ########################################################################################################## | |
| Param( | |
| [Parameter(Mandatory=$true)] | |
| [Microsoft.UpdateServices.Administration.IDatabaseConfiguration] $WSUSServerDB, | |
| [string] $LogFile = "Connect-WSUSDB.log" | |
| ) | |
| $component = "Connect-WSUSDB" | |
| #Determine the connection string based on the type of DB being used. | |
| If ($WSUSServerDB.IsUsingWindowsInternalDatabase){ | |
| #Using the Windows Internal Database. | |
| If (!$StandAloneWSUS){Add-TextToCMLog $LogFile "Windows Internal Database? Fer real? Come one dawg ... just stop this insanity and migrate this to your ConfigMgr SQL instance." $component 2} | |
| If($WSUSServerDB.ServerName -eq "MICROSOFT##WID"){ | |
| $SqlConnectionString = "Data Source=\\.\pipe\MICROSOFT##WID\tsql\query;Integrated Security=True;Network Library=dbnmpntw" | |
| } | |
| Else{ | |
| $SqlConnectionString = "Data Source=\\.\pipe\microsoft##ssee\sql\query;Integrated Security=True;Network Library=dbnmpntw" | |
| } | |
| } | |
| Else{ | |
| #Connect to a real SQL database. | |
| $SqlConnectionString = "Server=$($WSUSServerDB.ServerName);Database=$($WSUSServerDB.DatabaseName);Integrated Security=True" | |
| } | |
| #Try to connect to the database. | |
| Try{ | |
| $SqlConnection = New-Object System.Data.SqlClient.SqlConnection($SqlConnectionString) | |
| $SqlConnection.Open() | |
| Add-TextToCMLog $LogFile "Successfully connected to the database." $component 1 | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to connect to the database using the connection string $($SqlConnectionString)." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Return | |
| } | |
| Return $SqlConnection | |
| } | |
| Function Invoke-SQLCMD{ | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Run the SQL query passed and return the resulting data table. | |
| .DESCRIPTION | |
| Run the SQL query passed and return the resulting data table. | |
| #> | |
| ########################################################################################################## | |
| [OutputType([System.Data.DataTable])] | |
| Param( | |
| [Parameter(Mandatory=$true)] | |
| [System.Data.SqlClient.SqlConnection] $SqlConnection, | |
| [Parameter(Mandatory=$true)] | |
| [string] $SqlCommand, | |
| [string] $LogFile = "Invoke-SQLCMD.log" | |
| ) | |
| $component = "Invoke-SQLCMD" | |
| Try{ | |
| $SqlCmd = $SqlConnection.CreateCommand() | |
| $SqlCmd.CommandTimeout = 86400 #24 hours | |
| $SqlCmd.CommandText = $SqlCommand | |
| $SqlDataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd) | |
| [System.Data.DataTable] $DataTable = New-Object System.Data.DataTable | |
| [void]$SqlDataAdapter.Fill($DataTable) | |
| Return ,$DataTable #Force an array otherwise Powershell will return a DataRow instead of a DataTable if there's only one row. | |
| } | |
| Catch{ | |
| Add-TextToCMLog $LogFile "Failed to run the sql command: $SqlCommand." $component 3 | |
| Add-TextToCMLog $LogFile "Error ($($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Return | |
| } | |
| } | |
| Function Get-CatalogInfo{ | |
| ########################################################################################################## | |
| <# | |
| .SYNOPSIS | |
| Get information about the WSUS catalog. | |
| .DESCRIPTION | |
| Returns information about the WSUS catalog as a datatable including number of updates and both compressed and uncompressed XML size. | |
| #> | |
| [OutputType([System.Data.DataTable])] | |
| Param( | |
| [Parameter(Mandatory=$true)] | |
| [Microsoft.UpdateServices.Administration.IDatabaseConfiguration] $WSUSServerDB, | |
| [string] $LogFile = "Get-CatalogInfo.log" | |
| ) | |
| $SqlConnection = Connect-WSUSDB $WSUSServerDB $LogFile | |
| If(!$SqlConnection) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to connect to the WSUS database '$($WSUSServerDB.ServerName)'." $component 1 | |
| } | |
| else { | |
| $query = | |
| "Use $($WSUSServerDB.DatabaseName); | |
| ;with cte as | |
| ( | |
| SELECT dbo.tbXml.RevisionID, ISNULL(datalength(dbo.tbXml.RootElementXml), 0) as Uncompressed, ISNULL(datalength(dbo.tbXml.RootElementXmlCompressed), 0) as Compressed FROM dbo.tbXml | |
| INNER JOIN dbo.tbProperty ON dbo.tbXml.RevisionID = dbo.tbProperty.RevisionID | |
| ) | |
| Select | |
| Count(Distinct(u.LocalUpdateId)) As [UpdateCount], | |
| SUM(cte.Uncompressed) /1048576 as [CatalogSize_MB], | |
| SUM(cte.Compressed) /1048576 as [CompressedCatalogSize_MB] | |
| From tbUpdate u | |
| inner join tbRevision r on u.LocalUpdateID = r.LocalUpdateID | |
| inner join tbProperty pr on pr.RevisionID = r.RevisionID | |
| inner join cte on cte.revisionid = r.revisionid | |
| where r.RevisionID in | |
| ( | |
| Select t1.RevisionID | |
| From tbBundleAll t1 | |
| Inner Join tbBundleAtLeastOne t2 | |
| On t1.BundledID=t2.BundledID | |
| Where ishidden=0 and pr.ExplicitlyDeployable=1 | |
| )" | |
| return Invoke-SQLCMD $SqlConnection $query $LogFile | |
| } | |
| } | |
| #endregion | |
| $cmSiteVersion = [version]"5.00.8540.1000" | |
| $scriptVersion = "2.5.1" | |
| $component = 'Invoke-DGASoftwareUpdateMaintenance' | |
| $scriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent | |
| Write-Verbose -Message "Script Path: $scriptPath" | |
| $scriptFile = Split-Path -Path $MyInvocation.MyCommand.Definition -Leaf | |
| Write-Verbose -Message "Script File: $scriptFile" | |
| $IndexArray = @{ | |
| 'tbLocalizedProperty' = 'LocalizedPropertyID' | |
| 'tbLocalizedPropertyForRevision'='LocalizedPropertyID' | |
| 'tbRevision' = 'RowID, RevisionID' | |
| 'tbRevisionSupersedesUpdate' = 'SupersededUpdateID' | |
| } | |
| #region Parameter validation | |
| #If using a configuration file. | |
| If ($PSCmdlet.ParameterSetName -eq 'configfile' -and [string]::IsNullOrEmpty($ConfigFile)){ | |
| $ConfigFile = Join-Path -Path $scriptPath -ChildPath 'config.ini' | |
| Write-Verbose "No parameters were found. Using default configuration file" | |
| } | |
| #If a configuration file was specified the read the parameters from the file. | |
| If ($ConfigFile){ | |
| #Resolve the path if it's relative. | |
| Try{ | |
| $ConfigFilePath = Resolve-Path ($ConfigFile) -ErrorAction Stop | |
| Write-Verbose "Configuration File: $ConfigFilePath" | |
| $ConfigFile=$ConfigFilePath | |
| } | |
| Catch{ | |
| Write-Error "Could not resolve the the path to the configuration file '$ConfigFile'" | |
| Exit | |
| } | |
| If (Test-path $ConfigFile -PathType Leaf) { | |
| #Try loading the configuration file content. | |
| Try{ | |
| $FileContent = Get-Content $ConfigFile | |
| } | |
| Catch { | |
| Write-Error "The configuration file '$ConfigFile' cannot be read." | |
| Exit | |
| } | |
| #Loop through each line splitting on the first equal sign. | |
| ForEach ($Line in $FileContent){ | |
| #Skip lines that are empty, INI comments, or INI sections. | |
| If ([string]::IsNullOrEmpty($Line) -or (@('[',';',' ') -contains $Line[0])){Continue} | |
| #Split the line on the first equal sign and clean up the name. | |
| $Data = $Line.Split("=",2) | |
| $Data[0]=$Data[0].Trim() | |
| #If there's no value then treat it like a switch. Otherwise, process the value. | |
| If($Data.Count -eq 2){ | |
| If ($Data[0] -eq 'SiteCode') { #force a numeric SiteCode to be a string | |
| $Data[1]=[string]$Data[1].Trim() | |
| } Else { | |
| $Data[1]=$Data[1].Trim() | |
| } | |
| #Try to evaluate the value as an expression otherwise use the value as-is. | |
| Write-Verbose -Message "trying to Set Variable [$($Data[0])] to [$($Data[1])]" | |
| Try{ | |
| If ($Data[0] -eq 'SiteCode') { #force a numeric SiteCode to be a string | |
| Set-Variable -Name $Data[0] -Value ($Data[1] -as [string]) -Force -WhatIf:$False | |
| } ElseIf ($Data[1] -match "^\\\\\w*" -or $Data[1] -match "^[a-zA-Z]:\\\w*") { #match a local or UNC path | |
| Set-Variable -Name $Data[0] -Value ($Data[1] -as [string]) -Force -WhatIf:$False | |
| } ElseIf ($Data[1] -match "^@." -or $Data[1] -match "$*") { | |
| Set-Variable -Name $Data[0] -Value (Invoke-Expression $Data[1]) -Force -WhatIf:$False | |
| } ElseIf ($Data[1] -match "^[0-9]*$") { #case where entire value is numeric | |
| Set-Variable -Name $Data[0] -Value ($Data[1] -as [int]) -Force -WhatIf:$False | |
| } Else { | |
| Set-Variable -Name $Data[0] -Value ($Data[1] -as [string]) -Force -WhatIf:$False | |
| } | |
| } Catch{ | |
| Set-Variable -Name $Data[0] -Value $Data[1] -Force -WhatIf:$False | |
| } | |
| } | |
| ElseIf ($Data.Count -eq 1) { | |
| Set-Variable -Name $Data[0] -Value $True -Force -WhatIf:$False | |
| } | |
| Write-Verbose "Parameter $((Get-Variable $Data[0]).Name) is set to $((Get-Variable $Data[0]).Value) and is of [$($((Get-Variable $Data[0]).Value.GetType()))] type." | |
| } | |
| } | |
| Else{ | |
| Write-Error "The configuration file '$ConfigFile' cannot be found." | |
| Exit | |
| } #Config file exists. | |
| } #If config file was passed. | |
| #If log file is null then set it to the default and then make the provider type explicit. | |
| If ([string]::IsNullOrEmpty($LogFile)) { | |
| $LogFile = Join-Path -Path $scriptPath -ChildPath $([System.IO.Path]::ChangeExtension($ScriptFile, 'log')) | |
| Write-Verbose -Message "setting Log File to default" | |
| } | |
| Write-Verbose -Message "Log File: $LogFile" | |
| $LogFile = "filesystem::$($LogFile)" | |
| #If output file was given then make sure everything looks good. | |
| If (Test-Path -Path 'variable:UpdateListOutputFile'){ | |
| #If this was passed as a switch then use the default output file name. | |
| If (($UpdateListOutputFile -is [Boolean]) -or ($UpdateListOutputFile -eq 'True')){ | |
| $UpdateListOutputFile = Join-Path -Path $scriptPath -ChildPath $([System.IO.Path]::ChangeExtension($ScriptFile, 'csv')) | |
| } | |
| #If this was passed as a switch then use the default output file. | |
| If (![System.IO.Path]::IsPathRooted($UpdateListOutputFile)) { | |
| $UpdateListOutputFile = Join-Path -Path $scriptPath -ChildPath $UpdateListOutputFile | |
| } | |
| Write-Verbose "Output File: $UpdateListOutputFile" | |
| $UpdateListOutputFile = "filesystem::$($UpdateListOutputFile)" | |
| } | |
| #If the log file exists and is larger then the maximum then roll it over. | |
| If (Test-path $LogFile -PathType Leaf) { | |
| If ((Get-Item $LogFile).length -gt $MaxLogSize){ | |
| Move-Item -Force $LogFile ($LogFile -replace ".$","_") -WhatIf:$False | |
| } | |
| } | |
| Add-TextToCMLog $LogFile "$component started (Version $($scriptVersion))." $component 1 | |
| #Check to see if this script has ran recently. | |
| $lastRanPath = Join-Path -Path $scriptPath -ChildPath $([System.IO.Path]::ChangeExtension($ScriptFile, 'lastran')) #"filesystem::$(Join-Path $scriptPath "lastran_$($component)")" | |
| Write-Verbose "Last Ran Path: $lastRanPath" | |
| $lastRanPath = "filesystem::$($lastRanPath)" | |
| If (Test-Path -Path $lastRanPath -NewerThan ((Get-Date).AddHours(-24).ToString())) { | |
| #If the user has chosen to force the script to run or is running in WhatIf mode then run the script anyways. | |
| If ($Force -or $WhatIfPreference){ | |
| Add-TextToCMLog $LogFile "The script was run in the last 24 hours but is being forced to run." $component 1 | |
| } Else { | |
| Add-TextToCMLog $LogFile "The script was run in the last 24 hours. Use the Force parameter to run the script anyways." $component 2 | |
| Return | |
| } | |
| } | |
| #Mark the last time the script ran. We do this now and at the end to avoid running multiple instances of the script at the same time. | |
| If (!$WhatIfPreference){Get-Date | Out-File $lastRanPath -Force} | |
| #Check to make sure we're running this on a primary site server that has the SMS namespace. | |
| If (!($StandAloneWSUS) -and !(Get-WmiObject -namespace "Root" -class "__Namespace" -Filter "Name = 'SMS'")){ | |
| Add-TextToCMLog $LogFile "Currently, this script must be ran on a primary site server. When the CM 1706 reaches critical mass this requirement might be removed." $component 3 | |
| Return | |
| } | |
| #Make sure at least one action parameter was given. | |
| If (!$UseCustomIndexes -and !$RemoveCustomIndexes -and !$FirstRun -and !$DeleteDeclined -and !$DeclineSuperseded -and !$DeclineByTitle -and !$DeclineByPlugins -and !$RunCleanUpWizard -and !$CleanSUGs -and !$CombineSUGs -and !$UpdateADRDeploymentPackages -and !$CleanSources -and !$MaxUpdateRuntime) { | |
| Add-TextToCMLog $LogFile "You must choose one of the action parameters: UseCustomIndexes, RemoveCustomIndexes, FirstRun, DeleteDeclined, DeclineSuperseded, DeclineByTitle, DeclineByPlugins, RunCleanupWizard, CleanSUGs, CombineSUGs, UpdateADRDeploymentPackages, CleanSources, or MaximumUpdateRuntime." $component 3 | |
| Return | |
| } | |
| #Make sure the superseded updates parameters make sense. | |
| If (($ExclusionPeriod -or $DeclineLastLevelOnly) -and !$DeclineSuperseded -and !$DeleteDeclined){ | |
| Add-TextToCMLog $LogFile "You must use either the DeclineSuperseded or DeleteDeclined parameters when using the ExclusionPeriod or DeclineLastLevelOnly parameters." $component 3 | |
| Return | |
| } | |
| #Prevent ConfigMgr actions from being taken when running against a stand-alone WSUS server. | |
| If ($StandAloneWSUS -and ($ReSyncUpdates -or $CleanSUGs -or $CombineSUGs -or $UpdateADRDeploymentPackages -or $CleanSources -or $MaxUpdateRuntime)) { | |
| Add-TextToCMLog $LogFile "You may not use the following when running against a stand-alone WSUS: ReSyncUpdates, CleanSUGs, CombineSUGs, UpdateADRDeploymentPackages, CleanSources, or MaximumUpdateRuntime." $component 3 | |
| Return | |
| } | |
| #Make sure the stand-alone WSUS parameters make sense. | |
| If (!$StandAloneWSUS -and ($StandAloneWSUSPort -or $StandAloneWSUSSSL)) { | |
| Add-TextToCMLog $LogFile "You may not use the StandAloneWSUSPort or StandAloneWSUSSSL parameters when not running against a stand-alone WSUS." $component 3 | |
| Return | |
| } | |
| #Make sure the remove empty SUG parameter is only sent when cleaning up the SUGs. | |
| If ($RemoveEmptySUGs -and !$CleanSUGs){ | |
| Add-TextToCMLog $LogFile "You must use the RemoveEmptySUGs parameter with the CleanSUGs parameter." $component 3 | |
| Return | |
| } | |
| #Confirm that the string arrays are properly processed. | |
| $DeclineByTitle = Confirm-StringArray $DeclineByTitle | |
| $ExcludeByTitle = Confirm-StringArray $ExcludeByTitle | |
| $ExcludeByProduct = Confirm-StringArray $ExcludeByProduct | |
| #If the MaximumUpdateRuntime isn't a hashtable then see if it can be interpreted as such. | |
| If ($MaxUpdateRuntime){ | |
| If ($MaxUpdateRuntime.GetType() -eq [System.Collections.Hashtable]){ | |
| #Do nothing, the user successfully passed a hashtable. Good job user ... good job. | |
| } ElseIf ($MaxUpdateRuntime.GetType() -eq [System.String]){ | |
| #If the string doesn't contain valid newline characters but does contain semi-colons then swap them. | |
| If(($MaxUpdateRuntime -notmatch '`n') -and ($MaxUpdateRuntime -match ';')){ | |
| $MaxUpdateRuntime = $MaxUpdateRuntime.Replace(";","`n") | |
| } | |
| Try{ | |
| $MaxUpdateRuntime = ConvertFrom-StringData $MaxUpdateRuntime | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to convert the MaximumUpdateRuntime value from a string to a hashtable. This parameter will be ignored." $component 2 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 2 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 2 | |
| $MaxUpdateRuntime = $null | |
| } | |
| #If it's a hashtable now, dance with rejoice and let the user know. Otherwise ... sad face. | |
| If ($MaxUpdateRuntime.GetType() -eq [System.Collections.Hashtable]){ | |
| Add-TextToCMLog $LogFile "The MaximumUpdateRuntime parameter was converted from a string to a hashtable with $($MaxUpdateRuntime.Count) values." $component 2 | |
| } Else { | |
| $MaxUpdateRuntime = $null | |
| Add-TextToCMLog $LogFile "Attempted to convert the MaximumUpdateRuntime value into a hashtable but could not. This parameter will be ignored" $component 2 | |
| } | |
| } Else { | |
| Write-Error "You must pass either a string or a hashtable for the -Hash parameter." | |
| } | |
| } | |
| #endregion | |
| #Try to load the UpdateServices module. | |
| #NOTE: I initially tried using the WSUS Powershell module but it was exponentially slower than the API calls. Instead of a seconds it took hours to get the update list. | |
| Try { | |
| [reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | out-null | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to load the UpdateServices module." $component 3 | |
| Add-TextToCMLog $LogFile "Please make sure that WSUS Admin Console is installed on this machine" $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #Try and figure out WSUS connection details based on the parameters given. | |
| If ($StandAloneWSUS){ | |
| $WSUSFQDN = $StandAloneWSUS | |
| #If a port wasn't passed then set the default the port based on the SSL setting. | |
| If (!$StandAloneWSUSPort){ | |
| If ($StandAloneWSUSSSL){ | |
| $WSUSPort = 8531 | |
| } | |
| Else{ | |
| $WSUSPort = 8530 | |
| } | |
| } | |
| Else{ | |
| $WSUSPort = $StandAloneWSUSPort | |
| } | |
| $WSUSSSL = $StandAloneWSUSSSL | |
| } | |
| Else{ | |
| #If the Configuration Manager module exists then load it. | |
| If (! $env:SMS_ADMIN_UI_PATH) | |
| { | |
| Add-TextToCMLog $LogFile "The SMS_ADMIN_UI_PATH environment variable is not set. Make sure the Configuration Manager console it installed." $component 3 | |
| Return | |
| } | |
| $configManagerCmdLetpath = Join-Path $(Split-Path $env:SMS_ADMIN_UI_PATH) "ConfigurationManager.psd1" | |
| If (! (Test-Path $configManagerCmdLetpath -PathType Leaf) ) | |
| { | |
| Add-TextToCMLog $LogFile "The ConfigurationManager Module file could not be found. Make sure the Configuration Manager console it installed." $component 3 | |
| Return | |
| } | |
| #You can't pass WhatIf to the Import-Module function and it spits out a lot of text, so work around it. | |
| $WhatIf = $WhatIfPreference | |
| $WhatIfPreference = $False | |
| $Verbose = $VerbosePreference | |
| $VerbosePreference = 'SilentlyContinue' | |
| Import-Module $configManagerCmdLetPath -Force | |
| $WhatIfPreference = $WhatIf | |
| $VerbosePreference = $Verbose | |
| Remove-Variable -Name WhatIf, Verbose -WhatIf:$false | |
| #Get the site code | |
| If (!$SiteCode){$SiteCode = Get-SiteCode} | |
| #Verify that the site code was determined | |
| If (!$SiteCode){ | |
| Add-TextToCMLog $LogFile "Could not determine the site code. If you are running CAS you must specify the site code. Exiting." $component 3 | |
| Return | |
| } | |
| #If the PS drive doesn't exist then try to create it. | |
| If (! (Test-Path "$($SiteCode):")) { | |
| Try{ | |
| Add-TextToCMLog $LogFile "Trying to create the PS Drive for site '$($SiteCode)'" $component 1 | |
| New-PSDrive -Name $SiteCode -PSProvider CMSite -Root "." -WhatIf:$False | Out-Null | |
| } Catch { | |
| Add-TextToCMLog $LogFile "The site's PS drive doesn't exist nor could it be created." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Return | |
| } | |
| } | |
| #Set and verify the location. | |
| Try{ | |
| Add-TextToCMLog $LogFile "Connecting to site: $($SiteCode)" $component 1 | |
| Push-Location -Path "$($SiteCode):" | Out-Null | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Could not set location to site: $($SiteCode)." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Return | |
| } | |
| #Make sure the site code exists on this server. | |
| $CMSite = Get-CMSite -SiteCode $SiteCode | |
| If (!$CMSite) { | |
| Add-TextToCMLog $LogFile "The site code $($SiteCode) could not be found." $component 3 | |
| Return | |
| } | |
| #Verify the site version meets the requirement. | |
| If ($CMSite.Version -lt $cmSiteVersion){ | |
| Write-Warning "$($ModuleName) requires Configuration Manager $($cmSiteVersion.ToString()) or greater." | |
| } | |
| Try { | |
| #Determine the active SUP. | |
| $WSUSFQDN = (((Get-CMSoftwareUpdatePointComponent -SiteCode $SiteCode).Props) | Where-Object {$_.PropertyName -eq 'DefaultWSUS'}).Value2 | |
| $ActiveSoftwareUpdatePoint = Get-CMSoftwareUpdatePoint -SiteCode $SiteCode -SiteSystemServerName $WSUSFQDN | |
| #Verify that an active SUP was found. | |
| If (!$ActiveSoftwareUpdatePoint){ | |
| Add-TextToCMLog $LogFile "The active software update point ($WSUSFQDN) could not be found." $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| Add-TextToCMLog $LogFile "The active software update point is $WSUSFQDN." $component 1 | |
| #Determine if the active SUP is using SSL and what port. | |
| $WSUSSSL = (($ActiveSoftwareUpdatePoint.Props) | Where-Object {$_.PropertyName -eq 'SSLWSUS'}).Value | |
| $WSUSPort = 8530 | |
| If ($WSUSSSL){ | |
| $WSUSPort = (($ActiveSoftwareUpdatePoint.Props) | Where-Object {$_.PropertyName -eq 'WSUSIISSSLPort'}).Value | |
| Add-TextToCMLog $LogFile "Trying to connect to $WSUSFQDN on Port $WSUSPort using SSL." $component 1 | |
| } Else { | |
| $WSUSPort = (($ActiveSoftwareUpdatePoint.Props) | Where-Object {$_.PropertyName -eq 'WSUSIISPort'}).Value | |
| Add-TextToCMLog $LogFile "Trying to connect to $WSUSFQDN on Port $WSUSPort." $component 1 | |
| } | |
| } | |
| Catch { | |
| Add-TextToCMLog $LogFile "Failed to determine the active software update point." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| $WSUSServer = $null | |
| Pop-Location | |
| Return | |
| } | |
| } #If Not StandAloneWSUS | |
| Try{ | |
| $WSUSServer = [Microsoft.UpdateServices.Administration.AdminProxy]::GetUpdateServer($WSUSFQDN, $WSUSSSL, $WSUSPort) | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to connect to the WSUS server $WSUSFQDN on port $WSUSPort with$(If(!$WSUSSSL){"out"}) SSL." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| $WSUSServer = $null | |
| Pop-Location | |
| Return | |
| } | |
| #If the WSUS object is not instantiated then exit. | |
| If ($null -eq $WSUSServer) { | |
| Add-TextToCMLog $LogFile "Failed to connect." $component 3 | |
| Add-TextToCMLog $LogFile "Please make sure that WSUS Admin Console is installed on this machine" $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| Add-TextToCMLog $LogFile "Connected to WSUS server $WSUSFQDN." $component 1 | |
| #If the user has chosen to add custom indexes to the WSUS database. | |
| If ($UseCustomIndexes){ | |
| Add-TextToCMLog $LogFile "User selected AddIndex. Will try to verify indexes and create where necessary." $component 1 | |
| $WSUSServerDB = Get-WSUSDB $WSUSServer $LogFile | |
| If(!$WSUSServerDB) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to get the WSUS database configuration." $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| $SqlConnection = Connect-WSUSDB $WSUSServerDB $LogFile | |
| If(!$SqlConnection) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to connect to the WSUS database '$($WSUSServerDB.ServerName)'." $component 3 | |
| } | |
| Else{ | |
| #Loop through the hashtable and create the indexes. | |
| $FailedIndex = $False | |
| ForEach ($TableName in $IndexArray.Keys){ | |
| #Determine if the index exists and create it if not. | |
| $Index = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);SELECT * FROM sys.indexes WHERE name='IX_DGA_$TableName' AND object_id = OBJECT_ID('$TableName')" $LogFile | |
| #If the index doesn't exist then create it. | |
| If($Index.Rows.Count -eq 0 ){ | |
| Add-TextToCMLog $LogFile "The index IX_DGA_$TableName does not exist and will be created." $component 1 | |
| If (!$WhatIfPreference){ | |
| #Add the index. | |
| $Index = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);CREATE NONCLUSTERED INDEX IX_DGA_$TableName ON $TableName($($IndexArray[$TableName]))" $LogFile | |
| #Verify that the index exists now. | |
| $Index = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);SELECT * FROM sys.indexes WHERE name='IX_DGA_$TableName' AND object_id = OBJECT_ID('$TableName')" $LogFile | |
| If($Index.Rows.Count -eq 0 ){ | |
| Add-TextToCMLog $LogFile "Failed to create the index IX_DGA_$TableName." $component 2 | |
| $FailedIndex = $True | |
| } | |
| Else{ | |
| Add-TextToCMLog $LogFile "Successfully created the index IX_DGA_$TableName." $component 1 | |
| } | |
| } | |
| } | |
| } #ForEach IndexArray | |
| If ($FailedIndex){ | |
| Add-TextToCMLog $LogFile "Some indexes failed to create." $component 1 | |
| } | |
| Else{ | |
| Add-TextToCMLog $LogFile "All indexes have been added or verified." $component 1 | |
| } | |
| #Disconnect from the database. | |
| $SqlConnection.Close() | |
| } #Connect-WSUSDB | |
| } | |
| #If the user has chosen to remove custom indexes to the WSUS database. | |
| If ($RemoveCustomIndexes){ | |
| Add-TextToCMLog $LogFile "User selected RemoveCustomIndexes. Will try to remove the custom indexes." $component 1 | |
| $WSUSServerDB = Get-WSUSDB $WSUSServer $LogFile | |
| If(!$WSUSServerDB) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to get the WSUS database configuration." $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| $SqlConnection = Connect-WSUSDB $WSUSServerDB $LogFile | |
| If(!$SqlConnection) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to connect to the WSUS database '$($WSUSServerDB.ServerName)'." $component 3 | |
| } | |
| Else{ | |
| #Loop through the hashtable and remove the indexes. | |
| $FailedIndex = $False | |
| ForEach ($TableName in $IndexArray.Keys){ | |
| #Determine if the index exists. | |
| $Index = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);SELECT * FROM sys.indexes WHERE name='IX_DGA_$TableName' AND object_id = OBJECT_ID('$TableName')" $LogFile | |
| #If the index exists then remove it. | |
| If($Index.Rows.Count -gt 0 ){ | |
| Add-TextToCMLog $LogFile "The index IX_DGA_$TableName exists and will be removed." $component 1 | |
| If (!$WhatIfPreference){ | |
| #Remove the index. | |
| $Index = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);DROP INDEX IX_DGA_$TableName ON $TableName" $LogFile | |
| #Verify that the index no longer exists. | |
| $Index = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);SELECT * FROM sys.indexes WHERE name='IX_DGA_$TableName' AND object_id = OBJECT_ID('$TableName')" $LogFile | |
| If($Index.Rows.Count -gt 0 ){ | |
| Add-TextToCMLog $LogFile "Failed to remove the index IX_DGA_$TableName." $component 2 | |
| $FailedIndex = $True | |
| } | |
| Else{ | |
| Add-TextToCMLog $LogFile "Successfully removed the index IX_DGA_$TableName." $component 1 | |
| } | |
| } | |
| } | |
| } #ForEach IndexArray | |
| If ($FailedIndex){ | |
| Add-TextToCMLog $LogFile "Some indexes failed to remove." $component 1 | |
| } | |
| Else{ | |
| Add-TextToCMLog $LogFile "All indexes have been removed." $component 1 | |
| } | |
| #Disconnect from the database. | |
| $SqlConnection.Close() | |
| } #Connect-WSUSDB | |
| } | |
| #If the user has used the FirstRun parameter. | |
| If($FirstRun){ | |
| Add-TextToCMLog $LogFile "User selected FirstRun. Will try to delete obsolete updates by directly calling the database store procedures." $component 1 | |
| If (!$UseCustomIndexes){Add-TextToCMLog $LogFile "You have chosen not to use the UseCustomIndexes feature. While the custom indexes are not supported by Microsoft the update deletion process can be painfully slow and it is recommended that you use them." $component 2} | |
| $WSUSServerDB = Get-WSUSDB $WSUSServer $LogFile | |
| If(!$WSUSServerDB) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to get the WSUS database configuration." $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| $SqlConnection = Connect-WSUSDB $WSUSServerDB $LogFile | |
| If(!$SqlConnection) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to connect to the WSUS database '$($WSUSServerDB.ServerName)'." $component 1 | |
| } | |
| Else{ | |
| $ObsoleteUpdates = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);exec spGetObsoleteUpdatesToCleanup" $LogFile | |
| Add-TextToCMLog $LogFile "Found $($ObsoleteUpdates.Rows.Count) obsolete updates to delete." $component 1 | |
| #Loop through each result and delete | |
| If ($WhatIfPreference) {Add-TextToCMLog $LogFile "The WhatIf parameter was sent. No obsolete updates will actually be deleted." $component 2} | |
| For ($i=0; $i -lt $ObsoleteUpdates.Rows.Count; $i++){ | |
| #Get the update details. This is done per-update to avoid any joins across large sets of data. A poorly maintained SUSDB doens't like those. Not one bit. | |
| $LocalUpdateIdRows = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);Select UpdateID from tbUpdate Where LocalUpdateID = $($ObsoleteUpdates.Rows[$i][0])" $LogFile | |
| If ($LocalUpdateIdRows.Rows.Count -gt 0){ | |
| $LocalUpdateId = $LocalUpdateIdRows.Rows[0][0] | |
| $UpdateTitleRows = Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);Select DefaultTitle from PUBLIC_VIEWS.vUpdate Where UpdateId = '$LocalUpdateId'" $LogFile | |
| If ($UpdateTitleRows.Rows.Count -gt 0){ | |
| $UpdateTitle = $UpdateTitleRows.Rows[0][0] | |
| } | |
| Else{ | |
| $UpdateTitle = 'Unknown' | |
| } | |
| } | |
| Else{ | |
| $LocalUpdateId = 'Unknown' | |
| $UpdateTitle = 'Unknown' | |
| } | |
| #Track the progress all pretty-like. | |
| $percentComplete = [math]::Round(($i/$ObsoleteUpdates.Rows.Count) * 100) | |
| Write-Progress -Activity "Deleting Obsolete Updates" -Status "Deleting update '$($UpdateTitle)' ($($LocalUpdateId)) ($($i)/$($ObsoleteUpdates.Rows.Count))" -PercentComplete $percentComplete -CurrentOperation "$($percentComplete)% complete" | |
| Add-TextToCMLog $LogFile "Attempting to delete update '$($UpdateTitle)' ($($LocalUpdateId)) ($($i + 1)/$($($ObsoleteUpdates.Rows.Count)))." $component 1 | |
| If (!($WhatIfPreference)){ | |
| Invoke-SQLCMD $SqlConnection "Use $($WSUSServerDB.DatabaseName);exec spDeleteUpdate '$($ObsoleteUpdates.Rows[$i][0])'" $LogFile | |
| } | |
| } | |
| #Clear the progress bar | |
| Write-Progress -Activity "Deleting Obsolete Updates" -Completed | |
| #Disconnect from the database. | |
| $SqlConnection.Close() | |
| } #Connect-WSUSDB | |
| } | |
| #If the user has decided to decline updates. | |
| $UpdatesToDecline = @{} #Hash table updates to decline. | |
| $UpdatesToDelete = @{} #Hash table updates to delete. | |
| If ($DeleteDeclined -or $DeclineSuperseded -or $DeclineByTitle -or $DeclineByPlugins){ | |
| $WSUSServerDB = Get-WSUSDB $WSUSServer $LogFile | |
| If(!$WSUSServerDB) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to get the WSUS database configuration." $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| #Check the sync status. | |
| If ($StandAloneWSUS){ | |
| Invoke-WSUSSyncCheck $WSUSServer $LogFile | |
| } | |
| Else{ | |
| Invoke-CMSyncCheck $LogFile | |
| } | |
| #Get a collection of all updates. | |
| Add-TextToCMLog $LogFile "Retrieving all updates." $component 1 | |
| Try { | |
| If ($WhatIfPreference){ $Global:AllUpdates = $null } #if in WhatIf mode, make $AllUpdates a global variable so it can be used after the script exits | |
| $AllUpdates = $WSUSServer.GetUpdates() | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get updates." $component 3 | |
| Add-TextToCMLog $LogFile "If this operation timed out, try running the script with only the FirstRun parameter." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Pop-Location | |
| Return | |
| } | |
| Add-TextToCMLog $LogFile "Retrieved list of updates." $component 1 | |
| #Check the sync status. | |
| If ($StandAloneWSUS){ | |
| Invoke-WSUSSyncCheck $WSUSServer $LogFile | |
| } | |
| Else{ | |
| Invoke-CMSyncCheck $LogFile | |
| } | |
| #If dat file is null then set it to the default and then make the provider type explicit. | |
| #$datFilePath = "filesystem::$(Join-Path $scriptPath 'updatemaint.dat')" | |
| If ([string]::IsNullOrEmpty($datFile)) { | |
| $datFile = Join-Path -Path $scriptPath -ChildPath $([System.IO.Path]::ChangeExtension($ScriptFile, 'dat')) | |
| Write-Verbose -Message "setting Dat File to default" | |
| } | |
| Write-Verbose -Message "Dat File: $datFile" | |
| $datFile = "filesystem::$($datFile)" | |
| [Hashtable]$DeclinedUpdateData = @{} | |
| If (Test-Path $datFile){[Hashtable]$DeclinedUpdateData = Import-Clixml -Path $datFile} | |
| Add-TextToCMLog $LogFile "Loaded $($DeclinedUpdateData.Count) declined updates from the data file $datFile." $component 1 | |
| #Divide the updates list between declined or not. | |
| #This isn't strictly necessary but helps prevents myself or the plugins from trying to re-decline an update. | |
| $DeclinedUpdates = $AllUpdates | Where-Object {$_.IsDeclined -eq $True} | |
| $ActiveUpdates = $AllUpdates | Where-Object {$_.IsDeclined -eq $False} | |
| #Estimate catalog size | |
| if ($WSUSServerDB) | |
| { | |
| $CatalogInfo = Get-CatalogInfo $WSUSServerDB $LogFile | |
| $InitialCatlogSize="Unknown" | |
| $InitialCatlogSizeCompressed="Unknown" | |
| If($CatalogInfo.Rows.Count -gt 0 ){ | |
| $InitialCatlogSize=$CatalogInfo.Rows[0].CatalogSize_MB | |
| $InitialCatlogSizeCompressed=$CatalogInfo.Rows[0].CompressedCatalogSize_MB | |
| } | |
| } | |
| #Initialize count variables. | |
| $i = 0 | |
| $countDeleted = 0 | |
| $countSuperseded = 0 | |
| $countNewlyDeclined = 0 | |
| $countOther = 0 | |
| $countDeclinedSuperseded = 0 | |
| $countDeclinedByTitle = 0 | |
| $countDeclinedByTitleResults = @{} | |
| $countDeclinedByPlugin = 0 | |
| $countDeclinedByPluginResults = @{} | |
| ForEach ($SearchString In $DeclineByTitle){$countDeclinedByTitleResults[$SearchString]=0} | |
| #If no exclusion period was given then use the supersedence configuration of the SUP Component to calculate the exclusion date. | |
| If ($null -eq $ExclusionPeriod){ | |
| #If expiring immediately then use zero months otherwise use the number of months configured | |
| If ($StandAloneWSUS) { | |
| $ExclusionPeriod = 3 | |
| } | |
| Else { | |
| #Get the supersedence settings from ConfigMgr. | |
| $supersedenceMode = (((Get-CMSoftwareUpdatePointComponent -SiteCode $SiteCode).Props) | Where-Object {$_.PropertyName -eq 'Sync Supersedence Mode For NonFeature'}).Value | |
| #Verify that the product team didn't change these on us again. | |
| if ($null -eq $supersedenceMode) | |
| { | |
| $supersedenceMode = (((Get-CMSoftwareUpdatePointComponent -SiteCode $SiteCode).Props) | Where-Object {$_.PropertyName -eq 'Sync Supersedence Mode'}).Value | |
| if ($null -eq $supersedenceMode) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to determine ConfigMgr's supersedence mode. Exiting without making any changes." $component 3 | |
| return | |
| } | |
| } | |
| If ($supersedenceMode -eq 0){ | |
| $ExclusionPeriod = 0 | |
| } Else { | |
| $supersedenceAge = (((Get-CMSoftwareUpdatePointComponent -SiteCode $SiteCode).Props) | Where-Object {$_.PropertyName -eq 'Sync Supersedence Age For NonFeature'}).Value | |
| #Verify that the product team didn't change these on us again. | |
| if ($null -eq $supersedenceAge) | |
| { | |
| $supersedenceAge = (((Get-CMSoftwareUpdatePointComponent -SiteCode $SiteCode).Props) | Where-Object {$_.PropertyName -eq 'Sync Supersedence Age'}).Value | |
| if ($null -eq $supersedenceAge) | |
| { | |
| Add-TextToCMLog $LogFile "Failed to determine ConfigMgr's supersedence age. Exiting without making any changes." $component 3 | |
| return | |
| } | |
| } | |
| $ExclusionPeriod = $supersedenceAge | |
| } | |
| } | |
| } | |
| $ExclusionDate = (Get-Date).AddMonths($ExclusionPeriod * -1) | |
| #If deleting declined updates. | |
| If ($DeleteDeclined){ | |
| $ExclusionDateDelete = (Get-Date).AddMonths($ExclusionPeriod * -1) | |
| Add-TextToCMLog $LogFile "Deleting updates declined before $ExclusionDateDelete." $component 1 | |
| #Loop through declined updates. | |
| ForEach ($Update in $DeclinedUpdates) { | |
| #Check that the update is in the declined update data file. If not, add it with the current date. | |
| If($DeclinedUpdateData.ContainsKey($Update.Id.UpdateId)){ | |
| #Delete the updates if it's was declined before the exclusion date. | |
| If (([DateTime]$DeclinedUpdateData.($Update.Id.UpdateId)) -lt $ExclusionDateDelete) { | |
| #Add the update to the hash and count the number of superseded updates we decline. | |
| $UpdatesToDelete.Set_Item($Update.Id.UpdateId,"Declined") | |
| $countDeleted++ | |
| } | |
| } | |
| Else{ | |
| $DeclinedUpdateData.Set_Item($Update.Id.UpdateId,(Get-Date)) | |
| } | |
| } #ForEach DeclinedUpdates | |
| } #DeleteDeclined | |
| #If using the built-in logic for declining superseded updates. | |
| If($DeclineSuperseded){ | |
| Add-TextToCMLog $LogFile "Declining updates superseded for $ExclusionPeriod months (before $ExclusionDate)." $component 1 | |
| #Loop through updates and add those that match the user's criteria to the hash. | |
| ForEach ($Update in $ActiveUpdates) { | |
| #If we're declining superseded updates, and this update is superseded, and it's not already declined. | |
| If ($DeclineSuperseded -and $Update.IsSuperseded) { | |
| #Count the total number of superseded updates. | |
| $countSuperseded++ | |
| #Exclude superseded updates that do not meet the last level or exclusion period criteria. | |
| If ((($DeclineLastLevelOnly -and !$Update.HasSupersededUpdates) -or !$DeclineLastLevelOnly) -and (! (Test-Exclusions $Update))) { | |
| #Get the superseding updates. | |
| $SupersedingUpdates = $Update.GetRelatedUpdates([Microsoft.UpdateServices.Administration.UpdateRelationship]::UpdatesThatSupersedeThisUpdate) | |
| #Loop through the superseding updates. | |
| ForEach ($SupersedingUpdate in $SupersedingUpdates){ | |
| #If any of the superseding updates were created before the exclusion date then decline the superseded update. | |
| If ($SupersedingUpdate.CreationDate -le $ExclusionDate){ | |
| #Add the update to the hash and count the number of superseded updates we decline. | |
| $UpdatesToDecline.Set_Item($Update.Id.UpdateId,"Superseded") | |
| $countDeclinedSuperseded++ | |
| break | |
| } | |
| } | |
| } | |
| } | |
| } #ForEach Update | |
| } #DeclineSuperseded | |
| #If using the built-in logic for declining updates by title. | |
| If($DeclineByTitle){ | |
| Add-TextToCMLog $LogFile "Declining updates by title." $component 1 | |
| #Loop through updates and add those that match the user's criteria to the hash. | |
| ForEach ($Update in $ActiveUpdates) { | |
| #Loop through each title search string in the array and decline matching updates. | |
| ForEach ($SearchString In $DeclineByTitle) | |
| { | |
| #Find search string matches that aren't already declined by an earlier match. | |
| If (($Update.Title -ilike $SearchString) -and (! (Test-Exclusions $Update))) | |
| { | |
| #Add the update to the hash, count it, and set the AlreadyDeclined variable so we don't try to add it again. | |
| $UpdatesToDecline.Set_Item($Update.Id.UpdateId,"ByTitle: $SearchString") | |
| $countDeclinedByTitleResults[$SearchString]++ | |
| $countDeclinedByTitle++ | |
| } | |
| } | |
| } #ForEach Update | |
| } #DeclineByTitle | |
| #If using external logic then call the plugins. | |
| If($DeclineByPlugins){ | |
| #Check the sync status. | |
| If ($StandAloneWSUS){ | |
| Invoke-WSUSSyncCheck $WSUSServer $LogFile | |
| } | |
| Else{ | |
| Invoke-CMSyncCheck $LogFile | |
| } | |
| #Make sure the plugin folder exists. | |
| $PluginPath = "filesystem::$(Join-Path $scriptPath "Plugins")" | |
| If (!(Test-Path $PluginPath -PathType Container)){ | |
| Add-TextToCMLog $LogFile "DeclineByPlugins parameter was used but the plugins folder could not be found." $component 2 | |
| } Else { | |
| Add-TextToCMLog $LogFile "Enumerating and calling plugins." $component 1 | |
| #Loop through each powershell (.ps1) file in the plugin folder. | |
| ForEach($File in (Get-ChildItem (Join-path $PluginPath "*.ps1") )){ | |
| Add-TextToCMLog $LogFile "Running the $($File.BaseName) plugin." $component 1 | |
| Try{ | |
| #Dot source the file in. | |
| . $File | |
| } | |
| Catch { | |
| #Handle PowerShell ISE case where execution policy blocks dot-sourcing | |
| $PluginFileContent = Get-Content -Path $File | |
| Invoke-Expression -Command $PluginFileContent | |
| Remove-Variable -Name PluginFileContent | |
| } | |
| Try{ | |
| #Verify that the Invoke-SelectUpdatesPlugin command was loaded in from the plugin. | |
| If (! (Get-Command Invoke-SelectUpdatesPlugin -errorAction SilentlyContinue)) | |
| { | |
| Add-TextToCMLog $LogFile "The $($File.BaseName) plugin does not contain a function called Invoke-SelectUpdatesPlugin." $component 2 | |
| } Else { | |
| #Call the plugin function and get the returned hash. | |
| $pluginHash = Invoke-SelectUpdatesPlugin | |
| #Verify that the plugin returned a hash table. | |
| If ($pluginHash -IsNot [System.Collections.Hashtable]) { | |
| Add-TextToCMLog $LogFile "The $($File.BaseName) plugin did not return a hashtable object and was ignored." $component 2 | |
| } Else { | |
| #Remove duplicate items from the plugin hash. | |
| $duplicates = $UpdatesToDecline.keys | Where-Object {$pluginHash.ContainsKey($_)} | |
| ForEach ($item in $duplicates) { | |
| $pluginHash.Remove($item) | |
| } | |
| #Join the hash tables. | |
| $UpdatesToDecline += $pluginHash | |
| #Count the declined updates by plugin. | |
| $countDeclinedByPlugin += $pluginHash.Count | |
| $countDeclinedByPluginResults.Set_Item($File.BaseName,$pluginHash.Count) | |
| } | |
| } | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to load the $($File.BaseName) plugin and call Invoke-SelectUpdatesPlugin function." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } Finally { | |
| #Remove the plugin function, ignoring errors in case it wasn't loaded at all. | |
| Remove-Item function:\Invoke-SelectUpdatesPlugin -ErrorAction SilentlyContinue -WhatIf:$False | |
| } | |
| } #ForEach | |
| } #Plugin folder found. | |
| } #DeclineByPlugins parameter passed. | |
| #If updates were selected to be declined then decline them. | |
| Add-TextToCMLog $LogFile "$($UpdatesToDecline.Count) updates were selected to be declined." $component 1 | |
| If($DeleteDeclined){Add-TextToCMLog $LogFile "$($UpdatesToDelete.Count) updates were selected to be deleted." $component 1} | |
| If (($UpdatesToDecline.Count -gt 0) -or ($UpdatesToDelete.Count -gt 0)){ | |
| If ($UpdateListOutputFile){ | |
| If (Test-Path -Path $UpdateListOutputFile -PathType Leaf) { | |
| #Archive last output file | |
| $UpdateListOutputFileDate = Get-Date -Date ((Get-Item -Path $UpdateListOutputFile).LastWriteTime) -Format 'yyyyMMdd_HHmmss' | |
| $UpdateListOutputFileArchive = $UpdateListOutputFileDate + [System.IO.Path]::GetExtension($UpdateListOutputFile) | |
| Write-Verbose -Message "Update List Output File Archive: $([System.IO.Path]::ChangeExtension($UpdateListOutputFile, $UpdateListOutputFileArchive))" | |
| Move-Item -Path $UpdateListOutputFile -Destination $([System.IO.Path]::ChangeExtension($UpdateListOutputFile, $UpdateListOutputFileArchive)) -WhatIf:$false | |
| } | |
| "Update Id,Revision Number,Title,KB Articles,Security Bulletin,Has Superseded Updates,Creation Date,Declined Reason" | Out-File $UpdateListOutputFile -Force -Encoding Default -WhatIf:$False} | |
| #Loop through updates and decline those that have been selected. | |
| ForEach ($Update in $AllUpdates) { | |
| #Track progress. | |
| $i++ | |
| $percentComplete = [math]::Round((($i/($AllUpdates.Count)) * 100)) | |
| Write-Progress -Activity "Processing Updates" -Status "Processing update $i/$($AllUpdates.Count) - $($Update.Id.UpdateId)" -PercentComplete $percentComplete -CurrentOperation "$($percentComplete)% complete" | |
| #If the update ID is in the decline or delete update hashes. | |
| If ($UpdatesToDecline.ContainsKey($Update.Id.UpdateId) -or $UpdatesToDelete.ContainsKey($Update.Id.UpdateId)){ | |
| Try | |
| { | |
| #For performance reasons don't check the sync status when in WhatIf mode. | |
| If (!$WhatIfPreference){ | |
| #Check the sync status. | |
| If ($StandAloneWSUS){ | |
| Invoke-WSUSSyncCheck $WSUSServer $LogFile | |
| } | |
| Else{ | |
| Invoke-CMSyncCheck $LogFile | |
| } | |
| } | |
| #Decline the update. | |
| If ($UpdatesToDecline.ContainsKey($Update.Id.UpdateId)){ | |
| If (!$WhatIfPreference){$Update.Decline()} | |
| $Action = 'Declined' | |
| $Source = $UpdatesToDecline.($Update.Id.UpdateId) | |
| $countNewlyDeclined++ | |
| #Save the declined date. | |
| $DeclinedUpdateData.Set_Item($Update.Id.UpdateId, (Get-Date)) | |
| } | |
| #Delete the update. | |
| If ($UpdatesToDelete.ContainsKey($Update.Id.UpdateId)){ | |
| If (!$WhatIfPreference){$WSUSServer.DeleteUpdate($Update.Id.UpdateId)} | |
| $Action = 'Deleted' | |
| $Source = $UpdatesToDelete.($Update.Id.UpdateId) | |
| $DeclinedUpdateData.Remove($Update.Id.UpdateId) | |
| $countNewlyDeleted++ | |
| } | |
| #Log what we've done. | |
| If ($WhatIfPreference) { $Action = 'WhatIf' + ' ' + $Action} | |
| Add-TextToCMLog $LogFile "$Action update '$($Update.Title)' (ID: $($Update.Id.UpdateId)). Source: $Source" $component 1 | |
| If ($UpdateListOutputFile){"$($Update.Id.UpdateId),$($Update.Id.RevisionNumber),""$($Update.Title)"",$($Update.KnowledgeBaseArticles),$($Update.SecurityBulletins),$($Update.HasSupersededUpdates),$($Update.CreationDate),$Source" | Out-File $UpdateListOutputFile -Append -Encoding Default -WhatIf:$False} | |
| } | |
| Catch [System.Exception] | |
| { | |
| Add-TextToCMLog $LogFile "Failed to decline update '$($Update.Title)' (ID: $($Update.Id.UpdateId)). Source: $($UpdatesToDecline.($Update.Id.UpdateId)) Error: $($_.Exception.Message)." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } | |
| #Clear the progress bar | |
| Write-Progress -Activity "Processing Updates" -Completed | |
| } | |
| #Restimate catalog size | |
| if ($WSUSServerDB) | |
| { | |
| $NewCatalogInfo = Get-CatalogInfo $WSUSServerDB $LogFile | |
| If($NewCatalogInfo.Rows.Count -gt 0 ){ | |
| $InitialCatlogSize=$NewCatalogInfo.Rows[0].CatalogSize_MB | |
| $InitialCatlogSizeCompressed=$NewCatalogInfo.Rows[0].CompressedCatalogSize_MB | |
| } | |
| } | |
| #Write the summary information. | |
| If ($UpdateListOutputFile){Add-TextToCMLog $LogFile "List of declined updates: $UpdateListOutputFile" $component 1} | |
| If ($WhatIfPreference){ Add-TextToCMLog $LogFile "NOTE: The WhatIf flag was given so the below summary shows what would have happened. No changes were made." $component 2} | |
| Add-TextToCMLog $LogFile "Summary:" $component 1 | |
| Add-TextToCMLog $LogFile "========" $component 1 | |
| Add-TextToCMLog $LogFile "Initial Catalog Size = $InitialCatlogSize MB ($InitialCatlogSizeCompressed MB Compressed )" $component 1 | |
| Add-TextToCMLog $LogFile "All Updates = $($AllUpdates.Count)" $component 1 | |
| Add-TextToCMLog $LogFile "All Declined Updates = $($DeclinedUpdates.Count)" $component 1 | |
| Add-TextToCMLog $LogFile "All Updates Except Declined = $($ActiveUpdates.Count)" $component 1 | |
| If ($DeclineSuperseded) {Add-TextToCMLog $LogFile "All Superseded Updates = $countSuperseded" $component 1} | |
| If ($DeclineSuperseded) {Add-TextToCMLog $LogFile "Superseded Updates Declined = $countDeclinedSuperseded" $component 1} | |
| If ($DeclineByTitle) { | |
| ForEach ($result in $countDeclinedByTitleResults.Keys) { | |
| Add-TextToCMLog $LogFile "Updates Declined by Title for ${result} = $($countDeclinedByTitleResults.Item($result))" $component 1 | |
| } | |
| Add-TextToCMLog $LogFile "Updates Declined by Title (Total) = $countDeclinedByTitle" $component 1 | |
| } | |
| If ($DeclineByPlugins) { | |
| ForEach ($result in $countDeclinedByPluginResults.Keys) { | |
| Add-TextToCMLog $LogFile "Updates Declined by Plugin for ${result} = $($countDeclinedByPluginResults.Item($result))" $component 1 | |
| } | |
| Add-TextToCMLog $LogFile "Updates Declined by Plugin (Total Unique) = $countDeclinedByPlugin" $component 1 | |
| } | |
| Add-TextToCMLog $LogFile "Total Newly Declined Updates = $countNewlyDeclined" $component 1 | |
| If($DeleteDeclined){Add-TextToCMLog $LogFile "Total Newly Deleted Updates = $countDeleted" $component 1} | |
| Add-TextToCMLog $LogFile "Total Active Updates = $($AllUpdates.Count - $DeclinedUpdates.Count - $countNewlyDeclined)" $component 1 | |
| Add-TextToCMLog $LogFile "Total Updates = $($AllUpdates.Count - $countNewlyDeleted)" $component 1 | |
| If($NewCatalogInfo.Rows.Count -gt 0 ){ | |
| Add-TextToCMLog $LogFile "New Catalog Size = $($NewCatalogInfo.Rows[0].CatalogSize_MB) MB ($($NewCatalogInfo.Rows[0].CompressedCatalogSize_MB) MB Compressed )" $component 1 | |
| } | |
| Add-TextToCMLog $LogFile "========" $component 1 | |
| #Save the declined update data. | |
| If (!$WhatIfPreference){Export-Clixml -Path $datFile -InputObject $DeclinedUpdateData -Force} | |
| Add-TextToCMLog $LogFile "Saved $($DeclinedUpdateData.Count) declined updates to the data file $datFile." $component 1 | |
| } #If DeclineSuperseded, DeclineByTitle, or DeclineByPlugins | |
| #If selected, run the WSUS cleanup wizard now that we've declined a bunch of stuff. | |
| Try{ | |
| If ($RunCleanupWizard){ | |
| #Check the sync status. | |
| If ($StandAloneWSUS){ | |
| Invoke-WSUSSyncCheck $WSUSServer $LogFile | |
| } | |
| Else{ | |
| Invoke-CMSyncCheck $LogFile | |
| } | |
| Add-TextToCMLog $LogFile "Starting the WSUS cleanup wizard." $component 1 | |
| If ($WhatIfPreference){ | |
| Add-TextToCMLog $LogFile "Finished the WSUS cleanup wizard." $component 1 | |
| } Else { | |
| $cleanupScope = New-Object Microsoft.UpdateServices.Administration.CleanupScope; | |
| $cleanupScope.DeclineSupersededUpdates = $true | |
| $cleanupScope.DeclineExpiredUpdates = $true | |
| $cleanupScope.CleanupObsoleteUpdates = $true | |
| $cleanupScope.CompressUpdates = $true | |
| $cleanupScope.CleanupObsoleteComputers = $true | |
| $cleanupScope.CleanupUnneededContentFiles = $true | |
| $cleanupManager = $WSUSServer.GetCleanupManager(); | |
| $cleanupResults = $cleanupManager.PerformCleanup($cleanupScope); | |
| Add-TextToCMLog $LogFile "WSUS cleanup wizard has finished successfully:" $component 1 | |
| Add-TextToCMLog $LogFile " Disk Space Freed (bytes): $($cleanupResults.DiskSpaceFreed)." $component 1 | |
| Add-TextToCMLog $LogFile " Expired Updates Declined: $($cleanupResults.ExpiredUpdatesDeclined)." $component 1 | |
| Add-TextToCMLog $LogFile " Obsolete Computers Deleted: $($cleanupResults.ObsoleteComputersDeleted)." $component 1 | |
| Add-TextToCMLog $LogFile " Obsolete Updates Deleted: $($cleanupResults.ObsoleteUpdatesDeleted)." $component 1 | |
| Add-TextToCMLog $LogFile " Superseded Updates Declined: $($cleanupResults.SupersededUpdatesDeclined)." $component 1 | |
| Add-TextToCMLog $LogFile " Updates Compressed: $($cleanupResults.UpdatesCompressed)." $component 1 | |
| } | |
| } | |
| } | |
| catch [System.Exception] | |
| { | |
| Add-TextToCMLog $LogFile "Failed to run WSUS cleanup wizard." $component 3 | |
| Add-TextToCMLog $LogFile "You might need to run the WSUS cleanup wizard multiple times for complete success." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| $WSUSServer = $null | |
| } | |
| #If the ReSyncUpdates parameter was used then perform a full sync of updates and wait for it to complete. | |
| #By resyncing before cleaning the SUGs we can be certain to catch any newly declined/expired updates. | |
| If ($ReSyncUpdates){ | |
| Invoke-CMSyncCheck $LogFile | |
| #Try to initiate an update sync. | |
| Try | |
| { | |
| If(!$WhatIfPreference){Sync-CMSoftwareUpdate -FullSync $True} | |
| Add-TextToCMLog $LogFile "Initiated a full software update sync and waiting one minute for it to start." $component 1 | |
| If (!$WhatIfPreference) {Start-Sleep -Seconds 60} | |
| Invoke-CMSyncCheck $LogFile | |
| } | |
| Catch [System.Exception] | |
| { | |
| Add-TextToCMLog $LogFile "Failed to initiate a full update sync.)" $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| #Remove the updates declined above or expired by Microsoft. | |
| If ($CleanSUGs){ | |
| Add-TextToCMLog $LogFile "Cleaning the Software Update Groups." $component 1 | |
| #Get all the Software Update Groups. | |
| Try { | |
| $SoftwareUpdateGroups = Get-CMSoftwareUpdateGroup | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get software update groups." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #Loop through each group, get the updates, and remove those that have been declined or are expired. | |
| ForEach ($SoftwareUpdateGroup in $SoftwareUpdateGroups){ | |
| Add-TextToCMLog $LogFile "Cleaning the $($SoftwareUpdateGroup.LocalizedDisplayName) software update group." $component 1 | |
| $SoftwareUpdateGroupUpdates = Get-CMSoftwareUpdate -UpdateGroup $SoftwareUpdateGroup -Fast | |
| #Loop through each update and remove those that have been declined or are expired. | |
| ForEach($Update in $SoftwareUpdateGroupUpdates){ | |
| If ($Update.IsExpired -or ($UpdatesToDecline.ContainsKey($Update.CI_UniqueID))){ | |
| Add-TextToCMLog $LogFile "Removing $($Update.LocalizedDisplayName) from the $($SoftwareUpdateGroup.LocalizedDisplayName) software update group." $component 1 | |
| Try { | |
| If(!$WhatIfPreference){Remove-CMSoftwareUpdateFromGroup -SoftwareUpdate $Update -SoftwareUpdateGroup $SoftwareUpdateGroup -Force} | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get remove '$($Update.LocalizedDisplayName)' from the update group '$($SoftwareUpdateGroup.LocalizedDisplayName)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } | |
| #Delete SUGs that have no updates in them. | |
| If($RemoveEmptySUGs){ | |
| If ((Get-CMSoftwareUpdate -UpdateGroup $SoftwareUpdateGroup -Fast).Count -eq 0){ | |
| Add-TextToCMLog $LogFile "Removing the '$($SoftwareUpdateGroup.LocalizedDisplayName)' software update group because it is empty." $component 1 | |
| Try { | |
| Remove-CMSoftwareUpdateGroup -InputObject $SoftwareUpdateGroup -Force -WhatIf:$WhatIfPreference | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to remove the '$($SoftwareUpdateGroup.LocalizedDisplayName)' software update group." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } | |
| } | |
| } | |
| #Combine the SUGs into a yearly SUG leaving the passed in number of SUGs per ADR. | |
| If ($CombineSUGs){ | |
| Add-TextToCMLog $LogFile "Combining the software update groups into yearly groups leaving $($CombineSUGs) groups for each ADR." $component 1 | |
| #Try to get all the Software Update Groups. | |
| Try { | |
| $SoftwareUpdateGroups = Get-CMSoftwareUpdateGroup | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get software update groups." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #Try to get all the Automatic Deployment Rules. | |
| Try { | |
| $AutomaticDeploymentRules = Get-CMSoftwareUpdateAutoDeploymentRule -Fast | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get automatic deployment rules." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #Loop through each ADR and find matching SUGs. | |
| ForEach($AutomaticDeploymentRule in $AutomaticDeploymentRules){ | |
| #Get a list of SUGS sorted by descending creation date where the name matches the ADR and has a date. | |
| #This is an attempt the match ADRs to SUGs. While the SUG object has an AssociatedAutoRuleID property it is removed if the ADR is modified in any way. | |
| $ADRSUGs = $SoftwareUpdateGroups | Where-Object {$_.LocalizedDisplayName -match "$($AutomaticDeploymentRule.Name) \d\d\d\d-\d\d-\d\d"} | Sort-Object DateCreated -Descending | |
| #If there are more SUGS than the user wants, then add them to the yearly SUG. | |
| If ($ADRSUGs.Count -gt $CombineSUGs) { | |
| #Loop through each ADR SUG starting after the number the user wishes to keep. | |
| ForEach($i in $CombineSUGs..($ADRSUGs.Count-1)){ | |
| $SUG = $ADRSUGs[$i] | |
| Add-TextToCMLog $LogFile "Attempting to add '$($SUG.LocalizedDisplayName)' to a yearly software update group." $component 1 | |
| #Get the name of the yearly SUG name based on the ADR name plus the first four digits which are the year. | |
| $SUG.LocalizedDisplayName -match "$($AutomaticDeploymentRule.Name) \d\d\d\d" | Out-Null | |
| $YearlySUGName = $Matches[0] | |
| #Get the yearly SUG if it already exists. | |
| Try{ | |
| $YearlySUG = Get-CMSoftwareUpdateGroup -Name $YearlySUGName | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get the yearly software update group named '$($YearlySUG)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #If the yearly SUG didn't already exist then rename the current SUG and make it the yearly SUG. | |
| #Otherwise, add the SUG's updates to the yearly SUG and delete the SUG. | |
| If(!$YearlySUG){ | |
| Add-TextToCMLog $LogFile "Could not find a '$($YearlySUGName)' yearly software update group and will rename the '$($SUG.LocalizedDisplayName)' software update group." $component 1 | |
| Try{ | |
| Set-CMSoftwareUpdateGroup -InputObject $SUG -NewName $YearlySUGName -WhatIf:$WhatIfPreference | Out-Null | |
| $YearlySUG = $SUG | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to rename the '$($SUG.LocalizedDisplayName)' software update group." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } Else { | |
| #Try to add the SUG's updates to the yearly SUG. | |
| Try{ | |
| Add-TextToCMLog $LogFile "Adding the updates from the '$($SUG.LocalizedDisplayName)' software update group to the '$($YearlySUGName)' yearly software update group." $component 1 | |
| Get-CMSoftwareUpdate -UpdateGroup $SUG -Fast | Add-CMSoftwareUpdateToGroup -SoftwareUpdateGroup $YearlySUG -WhatIf:$WhatIfPreference | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to add the updates from the '$($SUG.LocalizedDisplayName)' software update group to the '$($YearlySUG.LocalizedDisplayName)' yearly software update group." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| #Skip to the next ADR SUG without removing the current one. | |
| Continue | |
| } | |
| #Try to delete the SUG. | |
| Try{ | |
| Add-TextToCMLog $LogFile "Removing the '$($SUG.LocalizedDisplayName)' software update group." $component 1 | |
| Remove-CMSoftwareUpdateGroup -InputObject $SUG -Force -WhatIf:$WhatIfPreference | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to delete the '$($SUG.LocalizedDisplayName)' software update group." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } #ForEach SUG. | |
| } #Found excess SUGs. | |
| } #ForEach ADR | |
| } | |
| #Set the maximum runtime for updates based on the passed in hashtable. | |
| If ($MaxUpdateRuntime){ | |
| #Loop through each value in the hash table. | |
| ForEach ($Value in $MaxUpdateRuntime.GetEnumerator()) { | |
| #$Get software updates that match the search string or warn if none are found or configure those that are. | |
| Add-TextToCMLog $LogFile "Setting the maximum runtime for updates matching '$($Value.Name)' to $($Value.Value) minutes." $component 1 | |
| $Updates = Get-CMSoftwareUpdate -Name $Value.Name -Fast -IsExpired $False | |
| If ($Updates.Count -eq 0){ | |
| Add-TextToCMLog $LogFile "No updates matched the search string '$($Value.Name)'." $component 2 | |
| } Else { | |
| $MaximumRuntimeSeconds = $Value.Value * 60 | |
| #Loop through each update and if the existing runtime doesn't match then try to change it. | |
| Foreach ($Update in $Updates){ | |
| If ($Update.MaxExecutionTime -ne $MaximumRuntimeSeconds){ | |
| Try{ | |
| If (!$WhatIfPreference){Set-CMSoftwareUpdate -InputObject $Update -MaximumExecutionMinutes $Value.Value} | |
| Add-TextToCMLog $LogFile "Set maximum runtime for '$($Update.LocalizedDisplayName)' to $($Value.Value) minutes." $component 1 | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to set maximum runtime for '$($Update.LocalizedDisplayName)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| #This is essentially a re-write of the content clean routine released by Microsoft here: | |
| # https://blogs.technet.microsoft.com/enterprisemobility/2012/04/12/software-update-content-cleanup-in-system-center-2012-configuration-manager/ | |
| If ($CleanSources){ | |
| If ($WhatIfPreference){ Add-TextToCMLog $LogFile "NOTE: The WhatIf flag was given so no changes will be made from the deployment package source folders." $component 2} | |
| #Loop through each deployment package | |
| ForEach ($UpdateDeploymentPackage in Get-CMSoftwareUpdateDeploymentPackage){ | |
| Add-TextToCMLog $LogFile "Cleaning update source files for $($UpdateDeploymentPackage.Name) with source path $($UpdateDeploymentPackage.PkgSourcePath)." $component 1 | |
| #Remove orphaned package-to-content relations that are not associated with CIs | |
| #TODO: I haven't seen this in the wild yet to test this method out so right now it just spits out to the log. | |
| $ContentQuery = "select pc.* from SMS_PackageToContent pc left join SMS_CIToContent cc on cc.ContentID=pc.ContentID where pc.PackageID=""$($UpdateDeploymentPackage.PackageID)"" and cc.ContentID is null" | |
| Foreach ($packageToContent in (Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Query $ContentQuery)){ | |
| Add-TextToCMLog $LogFile "The deployment package $($UpdateDeploymentPackage.Name) has orphaned content (ID: $($packageToContent.ContentID))." $component 2 | |
| } | |
| $PackageSourcePath="filesystem::$($UpdateDeploymentPackage.PkgSourcePath)" | |
| If (! (Test-Path $PackageSourcePath -PathType Container)){ | |
| Add-TextToCMLog $LogFile "The deployment package $($UpdateDeploymentPackage.Name)'s source path ($($UpdateDeploymentPackage.PkgSourcePath)) does not exist." $component 2 | |
| } Else { | |
| Try | |
| { | |
| #Get the list of content subfolders for the deployment package. | |
| $ContentSubFolders = (Get-WmiObject -Namespace "ROOT\SMS\site_$($SiteCode)" -Query "Select * from SMS_PackageToContent where PackageID='$($UpdateDeploymentPackage.PackageID)'").ContentSubFolder | |
| } | |
| Catch [System.Exception] | |
| { | |
| Add-TextToCMLog $LogFile "Failed to get the content folders from the SMS_PackageToContent WMI class for Package ID $($UpdateDeploymentPackage.PackageID) ." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #Loop though the folders in the deployment package source folder and delete any that are no longer referenced. | |
| ForEach($Folder in (Get-ChildItem $PackageSourcePath -Directory)){ | |
| If (! $ContentSubFolders.Contains($Folder.Name) ){ | |
| Try{ | |
| $FolderPath = Join-Path $PackageSourcePath $Folder.Name | |
| If(!$WhatIfPreference){Remove-Item $FolderPath -Recurse -Force} | |
| Add-TextToCMLog $LogFile "Removing folder '$($FolderPath)' from the deployment package $($UpdateDeploymentPackage.Name)." $component 1 | |
| } | |
| Catch [System.Exception] | |
| { | |
| Add-TextToCMLog $LogFile "Failed to remove folder $($FolderPath) from the deployment package $($UpdateDeploymentPackage.Name)." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| If ($UpdateADRDeploymentPackages){ | |
| #Set the deployment package period according to the parameter. | |
| If($UpdateADRDeploymentPackages -eq "Yearly"){ | |
| $DeploymentPackagePeriod = (Get-Date).Year | |
| } ElseIf ($UpdateADRDeploymentPackages -eq "Monthly") { | |
| $DeploymentPackagePeriod = Get-Date -Format 'yyMM' | |
| } | |
| #Make sure a valid parameter was sent. | |
| If (!$DeploymentPackagePeriod){ | |
| Add-TextToCMLog $LogFile "An invalid UpdateADRDeploymentPackages parameter was sent. The deployment packages were unchanged." $component 3 | |
| } Else { | |
| Add-TextToCMLog $LogFile "Verifying that all automatic deployment rules are using a deployment package for the $($DeploymentPackagePeriod) period." $component 1 | |
| #Try to get all the Automatic Deployment Rules. | |
| Try { | |
| $CMPSSuppressFastNotUsedCheck = $True | |
| $AutomaticDeploymentRules = Get-CMSoftwareUpdateAutoDeploymentRule | |
| $CMPSSuppressFastNotUsedCheck = $False | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get automatic deployment rules." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #Loop through each ADR. | |
| ForEach ($AutomaticDeploymentRule in $AutomaticDeploymentRules){ | |
| #Ignore any ADRs that are disabled. | |
| If(!$AutomaticDeploymentRule.AutoDeploymentEnabled){ | |
| Add-TextToCMLog $LogFile "Ignoring the '$($AutomaticDeploymentRule.Name)' automatic deployment rule because it is disabled. " $component 1 | |
| Continue #Go to the next ADR. | |
| } | |
| #Try to get the deployment package name. | |
| Try { | |
| $DeploymentPackageID = ([xml]$AutomaticDeploymentRule.ContentTemplate).ContentActionXML.PackageID | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get the deployment package ID for '$($AutomaticDeploymentRule.Name)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Continue #Go to the next ADR. | |
| } | |
| #Try to get the deployment package. | |
| Try { | |
| $DeploymentPackage = Get-CMSoftwareUpdateDeploymentPackage -Id $DeploymentPackageID | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to get the deployment package name for '$($AutomaticDeploymentRule.Name)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Continue #Go to the next ADR. | |
| } | |
| $CorrectDeploymentPackageName = $DeploymentPackage.Name -replace '\d\d\d\d$', $DeploymentPackagePeriod | |
| #If the deployment package name doesn't end in four digits then warning the user. | |
| If ($DeploymentPackage.Name -notmatch ".+?\d\d\d\d$"){ | |
| Add-TextToCMLog $LogFile "The deployment package '$($DeploymentPackage.Name)' for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule does not end in four digits and cannot be update automatically. If you want it updated automatically rename it to end in four digits representing either the year or month in YYMM form. " $component 2 | |
| #If the deployment package is already correct do nothing. | |
| } ElseIf($DeploymentPackage.Name -eq $CorrectDeploymentPackageName) { | |
| #Do nothing. | |
| #Otherwise update the ADR to use the correct deployment package. | |
| } Else { | |
| #Try to see if the correct deployment package exists. | |
| Try { | |
| $CorrectDeploymentPackage = Get-CMSoftwareUpdateDeploymentPackage -Name $CorrectDeploymentPackageName | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to search for the the deployment package '$($CorrectDeploymentPackageName)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| #If the correct deployment package doesn't exist then create it. | |
| If(!$CorrectDeploymentPackage){ | |
| Add-TextToCMLog $LogFile "The correct deployment package '$($CorrectDeploymentPackageName)' for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule does not exist and will be created." $component 1 | |
| #Make sure that the existing deployment package's source path ends in four digits just like its name. | |
| If ($DeploymentPackage.PkgSourcePath -notmatch ".+?\d\d\d\d$"){ | |
| Add-TextToCMLog $LogFile "The source path for deployment package '$($DeploymentPackage.Name)' for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule does not end in four digits and cannot be update automatically. If you want it updated automatically rename it to end in four digits representing either the year or month in YYMM form. " $component 2 | |
| } Else { | |
| #Calculate the new deployment package's source path and make sure it does not exist. | |
| $NewDeploymentPackageSourcePath = $DeploymentPackage.PkgSourcePath -replace '\d\d\d\d$', $DeploymentPackagePeriod | |
| If (Test-Path "filesystem::$($NewDeploymentPackageSourcePath)") { | |
| Add-TextToCMLog $LogFile "Could not create the new '$($CorrectDeploymentPackageName)' deployment package for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule. The source path '$($NewDeploymentPackageSourcePath)' already exists. " $component 3 | |
| } Else { | |
| #Try to create the new source path. | |
| Try { | |
| New-Item "filesystem::$($NewDeploymentPackageSourcePath)" -ItemType "directory" -Force -WhatIf:$WhatIfPreference | Out-Null | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to create a new deployment package source folder '$($NewDeploymentPackageSourcePath)'for the the deployment package '$($CorrectDeploymentPackageName)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Continue #Go to the next ADR. | |
| } | |
| #Try to create the new deployment package. | |
| Try { | |
| $CorrectDeploymentPackage = New-CMSoftwareUpdateDeploymentPackage -Name $CorrectDeploymentPackageName -Path $NewDeploymentPackageSourcePath -WhatIf:$WhatIfPreference | |
| Add-TextToCMLog $LogFile "Created the new '$($CorrectDeploymentPackageName)' deployment package with ID '$($CorrectDeploymentPackage.PackageID)'." $component 1 | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to create a new deployment package '$($CorrectDeploymentPackage.Name)' for the the '$($AutomaticDeploymentRule.Name)' automatic deployment rule." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| Continue #Go to the next ADR. | |
| } | |
| #Get and loop through each distribution of the current package and distribute the new one to it. | |
| Add-TextToCMLog $LogFile "Distributing the new '$($CorrectDeploymentPackageName)' deployment package." $component 1 | |
| $DeploymentPackageDistribution = Get-WmiObject -Namespace "ROOT\SMS\site_$($SiteCode)" -Query "SELECT Name, ContentServerType FROM SMS_PackageContentServerInfo WHERE ObjectID = '$($DeploymentPackage.PackageId)' And ContentServerID Not In (Select NALPath From SMS_MigrationDP)" | |
| ForEach ($Distribution in $DeploymentPackageDistribution){ | |
| Try { | |
| If ($WhatIfPreference){ | |
| #Do nothing since the new package wasn't really created which will cause the following lines to fail. | |
| } ElseIf($Distribution.ContentServerType -eq 1){ | |
| Start-CMContentDistribution -DeploymentPackageId $CorrectDeploymentPackage.PackageID -DistributionPointName ($Distribution.Name -replace "\\\\","") | |
| } ElseIf($Distribution.ContentServerType -eq 2){ | |
| Start-CMContentDistribution -DeploymentPackageId $CorrectDeploymentPackage.PackageID -DistributionPointGroupName $Distribution.Name | |
| } Else { | |
| Add-TextToCMLog $LogFile "Failed to deploy the new deployment package '$($CorrectDeploymentPackage.Name)' for the the '$($AutomaticDeploymentRule.Name)' automatic deployment rule to '$($Distribution.Name)'. The server type '$($Distribution.ContentServerType)' is unknown." $component 3 | |
| } | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to deploy the new deployment package '$($CorrectDeploymentPackage.Name)' for the the '$($AutomaticDeploymentRule.Name)' automatic deployment rule to '$($Distribution.Name)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } #Source path exists. | |
| } #Source path conforms to naming standard. | |
| } #Correct deployment package doesn't exist. | |
| #If the correct deployment package doesn't exist then warn the user and do nothing. | |
| If(!$CorrectDeploymentPackage -and (-not $WhatIfPreference)){ | |
| Add-TextToCMLog $LogFile "The correct deployment package '$($CorrectDeploymentPackageName)' for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule does not exist and could not be created." $component 3 | |
| } Else { | |
| #Try to change the ADR's deployment package to the correct one. | |
| Try { | |
| Add-TextToCMLog $LogFile "Changing the deployment package for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule from '$($DeploymentPackage.Name)' to '$($CorrectDeploymentPackageName)'." $component 1 | |
| If (!$WhatIfPreference){ | |
| #Do some XML voodoo to update the package ID. Boy wouldn't it be great to be able to properly get and set this with the cmdlets? | |
| [xml]$ContentTemplateXML = $AutomaticDeploymentRule.ContentTemplate | |
| $ContentTemplateXML.ContentActionXML.PackageId = $CorrectDeploymentPackage.PackageId | |
| $AutomaticDeploymentRule.ContentTemplate = $ContentTemplateXML.OuterXml | |
| $AutomaticDeploymentRule.Put() | |
| } | |
| } Catch { | |
| Add-TextToCMLog $LogFile "Failed to change the the deployment package for the '$($AutomaticDeploymentRule.Name)' automatic deployment rule to '$($CorrectDeploymentPackageName)'." $component 3 | |
| Add-TextToCMLog $LogFile "Error: $($_.Exception.HResult)): $($_.Exception.Message)" $component 3 | |
| Add-TextToCMLog $LogFile "$($_.InvocationInfo.PositionMessage)" $component 3 | |
| } | |
| } | |
| } #Deployment package needs to be changed. | |
| } #ForeEach ADR. | |
| } #Invalid parameter. | |
| } | |
| Add-TextToCMLog $LogFile "$component finished." $component 1 | |
| Add-TextToCMLog $LogFile "#############################################################################################" $component 1 | |
| Pop-Location | |
| Write-Output "The script completed successfully. Review the log file for detailed results." | |
| #Mark the last time the script ran if not ran with WhatIf | |
| If (!$WhatIfPreference){Get-Date | Out-File $lastRanPath -Force} | |
| Write-Debug -Message 'Complete script? Suspend script and interrogate $Updates, $DeclinedUpdates, etc.' |