Posted on 周六 18 九月 2021

Create Direct Rule and Query RUle Device Collection Using PowerShell


Create Direct Rule Device collections in sccm using powershell

Create Query Rule Device Collection Using PowerShell

Troubleshoot

Create Direct Rule Device collections in sccm using powershell

Script:

Replace $collectiondir, $collectionname and $computers before use.

# Create Direct Rule Device collections in sccm using powershell

    $collectiondir = C:\Users\sccmadmin\Desktop\Collection
    $collectionname = All Servers
    $computers = Get-Content C:\Users\sccmadmin\Desktop\Collection\Server_List.txt

    New-CMDeviceCollection -Name $collectionname -LimitingCollectionName All Systems
        Foreach($computer in $computers) {
            try { 
                Add-CMDeviceCollectionDirectMembershipRule -CollectionName $collectionname -ResourceID $(get-cmdevice -Name $computer).ResourceID
                }
            catch {
                Invalid client or direct membership rule may already exist: $computer | Out-File $collectiondir\$collectionname`_invalid.log -Append
                }
        }



1

2

3

4

5

Create Query Rule Device Collection Using PowerShell

Script:

# Create Query Rule Device collections in sccm using powershell

# 1. Define Variables
$collectiondir = C:\Users\sccmadmin\Desktop\Query
$collectionname = All Workstation
$Query = 'select * from SMS_R_SYSTEM where SMS_R_SYSTEM.OperatingSystemNameandVersion like "%workstation%"'

# 2. Create New Collection#
New-CMDeviceCollection -Name $collectionname -LimitingCollectionName All Systems

# 3. Add members in the collection using query rule method#
Add-CMDeviceCollectionQueryMembershipRule -CollectionName $collectionname -QueryExpression $Query -RuleName Query1 



If you need a collection of all servers, simple replace the %workstation% with %Server% in the query statement.

6

7

8

Troubleshoot

During running the script, I got into trouble. According to my tutorial, the query line goes like:

$Query = select * from SMS_R_SYSTEM where SMS_R_SYSTEM.OperatingSystemNameandVersion like %workstation%’”


So it’s double quotations marks wrap the key word workstation with single quotation marks, but in my environment this doesn’t work at first, for several times; then I changed it reversely to single quotation marks wrap double marks, and it worked:

$Query = 'select * from SMS_R_SYSTEM where SMS_R_SYSTEM.OperatingSystemNameandVersion like "%workstation%"'


Later I tried again the double marks outside, it also worked. This is tricky.

And also I found that the first line is not necessary, ‘cause it’s not used:

$collectiondir = C:\Users\sccmadmin\Desktop\Query


I’ve tested the script without this line and it worked too.