Adding Multiple Devices To SCCM Collection PowerShell

I recently needed to add a few hundred devices to a collection in SCCM. I couldn’t use a query to achieve this as there where no attributes that I could use. So it would have to be a direct query and I didn’t really want to manually add hundreds of servers as this would take a long time and PowerShell is a much easier and faster option. I decided to write a quick script to get a list of device from a txt file and do a loop to add each device to the specified collection.

First I need to open a PowerShell connect to SCCM I prefer to use Powershell ISE as I can edit and test my script while in one console. To connect go to the SCCM console On the blue drop down icon on the top left, click it and then choose Connect via Windows PowerShell ISE.

Coll1

Once PowerShell ISE is open you should see the connection script.  Just click run script at top of ISE to connect to SCCM. Coll2

Once in ISE copy the script below and change the collectioname, computers and logpath variables to the correct location and collection that you want to added to.  Below is what the script should look like when it run.

Coll3

$collectionname = “RDS Deploy Collection”
$Computers = Get-content “c:\temp\Server_List.txt”
$logpath = “c:\temp”
foreach($computer in $computers) {
try {
Write-Host “Adding $computer to $collectionname” -ForegroundColor Green
Add-CMDeviceCollectionDirectMembershipRule -CollectionName $collectionname -ResourceId (get-cmdevice -Name $computer).ResourceID
}
catch {
Write-Warning “Cannot add client $computer object may not exist”
$computer | Out-File “$logpath\$collectionname-invalid.log” -Append
$Error[0].Exception | Out-File “$logpath\$collectionname-invalid.log” -Append
}
}

There is also a log file that will be export to give devices that have not been added and the error exception generated by PowerShell.

Coll4