Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Restores ConfigMgr Site Maintenance Task Settings backed up using the 'Backup-CMSiteMaintenanceTaskSettings' script
## Restores ConfigMgr Site Maintenance Task settings from json files (backed up using the 'Backup-CMSiteMaintenanceTaskSettings' script ##
## Should be run on the Primary Site Server ##
## Should be run as administrator ##
[cmdletbinding()]
Param(
[Parameter(Position=0,Mandatory=$True)]
[ValidateNotNullorEmpty()]
[string]$SiteCode,
[Parameter(Position=1,Mandatory=$True)]
[ValidateNotNullorEmpty()]
[string]$BackupDirectory
)
Try
{
# Get the list of backed-up json files
$Files = Get-ChildItem $BackupDirectory -File -Filter "*.json" -ErrorAction Stop | Select -ExpandProperty FullName
}
Catch
{
$_
Return
}
# Flag for no changes
$NoChanges = $True
# Iterate through each file (maintenance task)
Foreach ($File in $Files)
{
Try
{
# Convert the file content from JSON format
$JSON = Get-Content -Path $File -ErrorAction Stop | Out-String | ConvertFrom-Json -ErrorAction Stop
}
Catch
{
$_
Continue
}
# Convert the JSON psobject to a hash table
$SavedSettings = @{}
$Names = $JSON | Get-Member -MemberType properties | Select-Object -ExpandProperty name
$Names | ForEach-Object {
$SavedSettings.Add($_,$JSON.$_)
}
# Get the corresponding maintenance task from WMI
Try
{
$MT = Get-WmiObject -Namespace ROOT\SMS\site_$SiteCode -Class SMS_SCI_SQLTask -Filter "TaskName='$($SavedSettings.TaskName)'" -ErrorAction Stop
}
Catch
{
$_
Continue
}
# Iterate through each backed-up setting
$SavedSettings.GetEnumerator() | foreach {
$SavedSetting = $_
# Get the current setting value from WMI
$CurrentSetting = $MT.Properties | Where {$_.Name -eq $SavedSetting.Name}
# If the backed-up setting does not match the current setting
If ($SavedSetting.Value -ne $CurrentSetting.Value)
{
# Output the setting values we will restore
Write-host "Updating Task '$($MT.TaskName)':" -ForegroundColor Yellow
Write-Host " Setting: $($SavedSetting.Name)"
Write-host " Current Value: $($CurrentSetting.Value)"
Write-host " Restored Value: $($SavedSetting.Value)"
# Flag that something was restored
$NoChanges = $False
# Set the new value in WMI
$MT.$($SavedSetting.Name) = $SavedSetting.Value
Try
{
[void]$MT.Put()
}
Catch
{
$_
}
}
}
}
# If no changes were detected
If ($NoChanges)
{
Write-Host "No differences were detected between the backed-up task settings and the current task settings"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment