The following script allows to create a collection in a specific folder in SCCM.
- Import of the SCCM module
- Check if the collection already exist
- Creation of the collection with a specific limiting collection if not already existing in the folder
To work properly, this script must be launched from a server with the SCCM Console installed.
##*===============================================
##* IMPORT CONFIGURATION MANAGER MODULE
##*===============================================
Write-Host "Importing SCCM PS Module”
# Import SCCM PS Module
Import-Module ($Env:SMS_ADMIN_UI_PATH.Substring(0,$Env:SMS_ADMIN_UI_PATH.Length-5) + '\ConfigurationManager.psd1')
##*===============================================
##* DECLARATIONS
##*===============================================
Write-Host "Declaring variables”
# SCCM Server
$SCCMSiteServer = "MySCCMServerName"
$SCCMSiteCode = "MySCCMSiteCode"
$CMSitePath = $SCCMSiteCode+ ":"
# Collection
$CollectionName = "MyCollection"
$LimitingCollectionName = "MyLimitingCollection"
$CollectionFolder = "MyFolder"
$CollectionFolderPath = ".\DeviceCollection\" + $CollectionFolder
Write-Host "SCCM Server Name is $SCCMSiteServer"
Write-Host "SCCM Site Code is $SCCMSiteCode"
Write-Host "Collection name is $CollectionName"
Write-Host "Limiting Collection is $LimitingCollectionName"
Write-Host "Collection will be created in $CollectionFolderPath"
##*===============================================
##* CREATE COLLECTION
##*===============================================
# Create folder in SCCM if not already existing
Write-Host "Creating folder $CollectionFolder if not already existing"
Set-Location $CMSitePath
Set-Location "DeviceCollection"
New-Item -Name $CollectionFolder
# Check the collection does not already exist and create it
$CollectionExist = Get-CMDeviceCollection -Name "$CollectionName"
If ($CollectionExist) {
Write-Host "The collection $CollectionName already exist"
Exit
}
Else {
Write-Host "The collection $CollectionName does not already exist"
Write-Host "Creating collection"
cd\
Try {
$CollectionItem = New-CMDeviceCollection -LimitingCollectionName $LimitingCollectionName -name $CollectionName -RefreshType manual
$CollectionMove = Move-CMObject -folderpath $CollectionFolderPath -inputobject $CollectionItem
Write-Host "Collection $CollectionName created"
}
Catch {
Write-Host "Exception caught in creating collection : $error[0]"
}
}