Saturday, 31 March 2018

SCCM Device Collection Details with No deployment

How to get SCCM collection names where No deployments are targetted?

Sometimes we may need to clear all the unwanted collection as part of our SCCM maintenance activity. Usually, we used to delete the device collection from the Assets and Compliance workspace, select Device Collections, check the collection members and it's targetted deployments, right click on the collection and delete. This task will take a lot of time if we have a huge number of collections in our organization, So I thought of to automate this process using PowerShell script.I have also included the collection's member count which will be helpful in case if we need to delete the collection based on the collection's member count

Please follow the below PowerShell script to check SCCM device collections with No deployment and delete it if the collection is no longer required.

We need to modify the report path in the 1st line of this script, highlighted in yellow

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$reportpath = "K:\OSDLogs\Result.csv" # Provide CSV path with CSV Name

Import-module ($Env:SMS_ADMIN_UI_PATH.Substring(0,$Env:SMS_ADMIN_UI_PATH.Length-5) + '\ConfigurationManager.psd1')
$SiteCode = Get-PSDrive -PSProvider CMSITE
Set-location $SiteCode":"
$details = @()
$CollectionList = Get-CmCollection | Where-Object {$_.CollectionID -notlike 'SMS*' -and $_.CollectionType -eq '2'} | Select-Object -Property Name,MemberCount,CollectionID,IsReferenceCollection

foreach ($Collection in $CollectionList)
{
    $NumCollectionMembers = $Collection.MemberCount
    $CollectionID = $Collection.CollectionID
    $GetDeployment = Get-CMDeployment | Where-Object {$_.CollectionID -eq $Collection.CollectionID}  
    if ($GetDeployment -eq $null)
    {
        $collectionName = $Collection.Name
        $Membercount = $Collection.MemberCount
        $Result = [ordered]@{
        Collection_NAME     = "$collectionName"
        Member_Count     = "$Membercount" }
        $Details += New-Object PSObject -Property $Result
    }
}

The output of this script will be as shown below - 












As per the above script, we are not deleting the collection which doesn't have any deployments targetted to it. If we wanted to delete the collections with no deployments targetted, we need to modify the script under "IF" loop as shown below. 

Please note: The collection will be deleted forcefully without no notifications as per the below script, you can make the modification if required

1
2
3
4
5
6
7
        Remove-CMCollection -Id $CollectionID -Force
        $collectionName = $Collection.Name
        $Membercount = $Collection.MemberCount
        $Result = [ordered]@{
        Collection_NAME     = "$collectionName"
        MemberCount     = "$Membercount" }
        $Details += New-Object PSObject -Property $Result

Click here to download the script