czwartek, 10 sierpnia 2017

Life Hacks - Removing Direct Membership Rules of Certain Type in Bulk

    Today I was cleaning up a collection with hundreds of direct membership rule entries. The previous approach was taken temporarily and has now been replaced with include membership rules. Now - even though it is very easy to add multiple computers to the collection via GUI, based on a chosen pattern with the usage of Create Direct Membership Rule Wizard, it is not so convenient to remove them as the window is not scalable and it only has three rows visible at the time:

The view of Membership rules tab in Collection Properties window

 
    Here is where a little script could come in handy and help to take care of this task.

Usage:
    Swap the following strings in the script below with the names from your SCOM infrastructure:

  • _CollectionId_ - put the ID of the target collection
  • _CollectionName_ - put the name of the target collection
  • _NamingRegExp_ -  put the regular expression fitting your needs. If you want to remove all rules, just put "*" or remove that part of the code: ...| ?{$_.RuleName -like "_NamingRegExp_"}...

     The code has to be saved as a .ps1 file and run on the SCCM server via PowerShell connected to SCCM site server.

Code:
$Rules = Get-CMDeviceCollectionDirectMembershipRule -CollectionId "_CollectionId_" | ?{$_.RuleName -like "_NamingRegExp_"}
foreach ($Rule in $Rules) {
 Write-Host Removing $Rule.RuleName Rule -Foreground Yellow
 Remove-CMDeviceCollectionDirectMembershipRule -CollectionId "_CollectionId_"  -ResourceId $Rule.ResourceID -Force
}

The output of the script

Additional Notes:
    I have experienced certain problems using this script on the systems with PowerShell version 4.0. I received the following error while trying to pass the ResourceID parameter to the Get-CMDeviceCollectionDirectMembershipRule cmdlet:


The error message received on a system with PowerShell 4.0

    Instead of troubleshooting the problem I created a workaround using a CollectionName parameter, you can use the code below in case you encounter similar issues:

$Rules = Get-CMDeviceCollectionDirectMembershipRule -CollectionName "_CollectionName_" | ?{$_.RuleName -like "_NamingRegExp_"}
foreach ($Rule in $Rules) {
                Write-Host Removing $Rule.RuleName Rule -Foreground Yellow
                Remove-CMDeviceCollectionDirectMembershipRule -CollectionName "_CollectionName_" -ResourceId $Rule.ResourceID -Force 
}

Brak komentarzy:

Prześlij komentarz