PowerShell script for SCCM (System Center Configuration Manager) cleanup activities

PowerShell script for SCCM (System Center Configuration Manager) cleanup activities:

# Specify the SCCM site code

$SiteCode = "PS1"


# Set the site server name

$SiteServer = "SCCMSERVER01"


# Connect to the SCCM site server

$Site = [Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine]::Connect("$SiteServer\$SiteCode")


# Delete expired client records

$ExpiredClients = Get-WmiObject -Namespace "root\sms\site_$SiteCode" -Class "SMS_R_System" -Filter "Client = 0 AND LastMPServerName = '$SiteServer' AND DATEDIFF(dd, LastDDR, GETDATE()) > 90"

foreach ($ExpiredClient in $ExpiredClients) {

    $Site.DeleteObject($ExpiredClient)

}


# Delete obsolete packages

$ObsoletePackages = $Site.GetObsoleteUpdates()

foreach ($ObsoletePackage in $ObsoletePackages) {

    $Site.DeleteObject($ObsoletePackage)

}


# Delete obsolete advertisements

$ObsoleteAdvertisements = $Site.GetObsoleteAdvertisements()

foreach ($ObsoleteAdvertisement in $ObsoleteAdvertisements) {

    $Site.DeleteObject($ObsoleteAdvertisement)

}


# Delete obsolete collections

$ObsoleteCollections = $Site.GetObsoleteCollections()

foreach ($ObsoleteCollection in $ObsoleteCollections) {

    $Site.DeleteObject($ObsoleteCollection)

}


# Delete obsolete software metering rules

$ObsoleteSoftwareMeteringRules = $Site.GetObsoleteSoftwareMeteringRules()

foreach ($ObsoleteSoftwareMeteringRule in $ObsoleteSoftwareMeteringRules) {

    $Site.DeleteObject($ObsoleteSoftwareMeteringRule)

}


# Delete obsolete status messages

$ObsoleteStatusMessages = $Site.GetObsoleteStatusMessages()

foreach ($ObsoleteStatusMessage in $ObsoleteStatusMessages) {

    $Site.DeleteObject($ObsoleteStatusMessage)

}


# Disconnect from the SCCM site server

$Site = $null


This script connects to the SCCM site server, then performs a series of cleanup activities including deleting expired client records, obsolete packages, advertisements, collections, software metering rules, and status messages. It's important to note that this is just an example script and may need to be customized to meet the specific needs of your organization.

PowerShell script for SCCM cleanup activities

 PowerShell script for SCCM cleanup activities

# Connect to the SCCM server

$SiteServer = "SCCMServerName" $SiteCode = "SiteCode" $SiteServerConnection = Connect-SiteServer -SiteServer $SiteServer -SiteCode $SiteCode # Delete inactive client records older than 90 days $InactiveClients = Get-CMDevice -InactiveDays 90 ForEach ($InactiveClient in $InactiveClients) { Remove-CMDevice -InputObject $InactiveClient -Force } # Delete expired and superseded software updates $ExpiredUpdates = Get-CMSoftwareUpdate -Expired $SupersededUpdates = Get-CMSoftwareUpdate -Superseded ForEach ($Update in ($ExpiredUpdates + $SupersededUpdates)) { Remove-CMSoftwareUpdate -InputObject $Update -Force } # Delete unused software update groups $UnusedUpdateGroups = Get-CMSoftwareUpdateGroup | Where-Object { $_.UpdateCount -eq 0 } ForEach ($UpdateGroup in $UnusedUpdateGroups) { Remove-CMSoftwareUpdateGroup -InputObject $UpdateGroup -Force } # Delete orphaned task sequences $OrphanedTaskSequences = Get-CMTaskSequence | Where-Object { $_.Package -eq $null } ForEach ($TaskSequence in $OrphanedTaskSequences) { Remove-CMTaskSequence -InputObject $TaskSequence -Force } # Disconnect from the SCCM server Disconnect-SiteServer -SiteServerConnection $SiteServerConnection


This script performs the following SCCM cleanup tasks:


This script performs the following SCCM cleanup tasks:

Deletes inactive client records older than 90 days
Deletes expired and superseded software updates
Deletes unused software update groups
Deletes orphaned task sequences

You can customize this script to include additional cleanup tasks as needed. Note that this script assumes you have the SCCM PowerShell module installed and that you have the necessary permissions to perform the cleanup tasks.

Here's a basic PowerShell script for performing SCCM cleanup activity

Here's a basic PowerShell script for performing SCCM cleanup activity:


 # Define SCCM server name and site code

$SCCMServerName = "SCCMServer"

$SiteCode = "ABC"


# Connect to SCCM server using the SCCM cmdlet

Import-Module ($Env:SMS_ADMIN_UI_PATH.Substring(0,$Env:SMS_ADMIN_UI_PATH.Length-5) + '\ConfigurationManager.psd1')

Set-Location "$($SiteCode):"


# Clean up expired updates

$ExpiredUpdates = Get-CMUpdate -Expired

ForEach ($Update in $ExpiredUpdates) {

    Write-Host "Deleting expired update: $($Update.LocalizedDisplayName)"

    Remove-CMUpdate -Update $Update

}


# Clean up old task sequences

$OldTaskSequences = Get-CMTaskSequence | Where-Object {$_.LastModifiedDate -lt (Get-Date).AddMonths(-6)}

ForEach ($TaskSequence in $OldTaskSequences) {

    Write-Host "Deleting old task sequence: $($TaskSequence.Name)"

    Remove-CMTaskSequence -TaskSequencePackage $TaskSequence

}


# Clean up orphaned content

Start-CMContentLibraryCleanup -DeleteOrphanedContent



This script connects to the SCCM server, cleans up expired updates, old task sequences, and orphaned content. You can customize it further to include other cleanup activities as needed. Please note that this script is only meant to serve as an example and you should test and modify it as appropriate for your specific environment before running it in production.

Powershell Script to refresh SCCM collections based on AD group names

I had a requirement to refresh collection members whenever the AD group is modified.

So the below script will refresh SCCM deployment collections which begins with ADG or AD from Active Directory. which was modified in the last hour.


$SCCMPrimaryserver = 'Server101'

$siteCode = 'ABC'

$currentTime = Get-Date

$oneHourAgo = $currentTime.AddHours(-1)

# Get all AD groups that were modified in the last hour

$modifiedGroups = Get-ADGroup -Filter {Modified -ge $oneHourAgo }

# Get the name of the  modified group which Begins with ADG or AD

$latestModifiedGroup = $modifiedGroups | where-object {$_.name -like 'ADG_*' -or $_.name -like 'AD_*'} | Select-Object Name

Foreach ($collection in $latestModifiedGroup){

Write-Host "Refreshing $collection"

$RefreshingCol= Get-WmiObject -Namespace "root\sms\site_$($siteCode)" -ComputerName $SCCMPrimaryserver -Class "SMS_Collection" -Filter "Name='$collection'"

# Refresh the collection

$RefreshingCol.RequestRefresh()

}


Script to check the Certificate on machine by Template name

Below is the Script to check the Certificate on machines by Template name

I used this script in MECM baseline to get output.


$certTemplate = "Company Computer"

$cert = Get-ChildItem 'Cert:\LocalMachine\My' | Where-Object{ $_.Extensions | Where-Object{ ($_.Oid.FriendlyName -eq 'Certificate Template Information') -and ($_.Format(0) -match $certTemplate) }}

If ($Cert){

$true

}Else{

$false}

PowerShell Script to Copy the contents to remote machine and trigger the installation

 # Define variables

$computers = "Machine1","Machine2","Machine3"

$sourcePath = "C:\temp\Client"  # source path

# Copy the file to each remote computer

foreach ($computer in $computers) {

    Copy-Item -Path $sourcePath -Destination "\\$computer\C$\temp" -Recurse

}

# Install the software on each remote computer

foreach ($computer in $computers) {

    $process = [WMICLASS]"\\$computer\ROOT\CIMV2:Win32_Process"

    $process.Create("C:\Temp\Client\Client_upgrade.bat") # cmd line here with path where it has been copied 

}



Powershell Script to export SSRS subscriptions from One SSRS to Another

Here is a PowerShell script that can be used to export subscriptions from one Microsoft SQL Server Reporting Services (SSRS) server and import them to another SSRS server:

# Load the ReportingServices libraries [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Management.ReportingServices") # Connect to the source SSRS server $sourceServer = "SourceServerName" $sourceSsrs = New-WebServiceProxy -Uri "http://$sourceServer/ReportServer/ReportService2010.asmx?WSDL" -Namespace SSRS.ReportingService2010 -UseDefaultCredential # Get a list of all subscriptions on the source SSRS server $subscriptions = $sourceSsrs.ListSubscriptions("/") # Export the subscriptions to a CSV file $subscriptions | Select-Object Path, Report, EventType, @{Name="DeliveryExtension";Expression={$_.Extension}}, @{Name="Description";Expression={$_.Description}} | Export-Csv "Subscriptions.csv" -NoTypeInformation # Disconnect from the source SSRS server $sourceSsrs = $null # Connect to the destination SSRS server $destinationServer = "DestinationServerName" $destinationSsrs = New-WebServiceProxy -Uri "http://$destinationServer/ReportServer/ReportService2010.asmx?WSDL" -Namespace SSRS.ReportingService2010 -UseDefaultCredential # Load the subscriptions from the CSV file $subscriptions = Import-Csv "Subscriptions.csv" # Loop through each subscription in the CSV file foreach ($subscription in $subscriptions) { # Create a new subscription for each entry in the CSV file $newSubscription = New-Object Microsoft.SqlServer.Management.ReportingServices.Execution.ReportExecutionService.Subscription $newSubscription.Path = $subscription.Path $newSubscription.Extension = $subscription.DeliveryExtension $newSubscription.EventType = [Microsoft.SqlServer.Management.ReportingServices.Execution.ReportExecutionService.EventType]::$($subscription.EventType) $newSubscription.Description = $subscription.Description # Create the new subscription $destinationSsrs.CreateSubscription($newSubscription) } # Disconnect from the destination SSRS server $destinationSsrs = $null


This script starts by loading the ReportingServices libraries and connecting to the source SSRS server using the New-WebServiceProxy cmdlet. It then retrieves a list of all subscriptions on the source SSRS server using the ListSubscriptions method of the $sourceSsrs object.

The list of subscriptions is then exported to a CSV file using the Export-Csv cmdlet. The properties that are exported include the path of the report, the name of the report, the type of event that triggers the subscription, the delivery extension used to send the report, and the description of the subscription.

The script then disconnects from the source SSRS server and connects to the destination SSRS server using the New-WebServiceProxy cmdlet. The subscriptions from the CSV file are then imported and used to create new subscriptions on the destination SSRS server using