Need to add machines into a collection using powershell
Question
Dear Team,
Could someone please provide a script to add machines into a collection using powershell script.
Requirement:
We have an excel file that contains hostnames in column A and collection names in column B.
I want to read that excel file accordingly and add it into a respective collections.
Thanks in advance
Answers ( 3 )
Hello All,
Apologies for not being responded, I have created a powershell script to add the machines one by one.
Param(
$SiteCode = ‘mentionsitecodehere’,
[parameter(Mandatory=$true, ValueFromPipeline=$true)] $FilePath
)
function GetCMSiteConnection ($siteCode)
{
$CMModulePath = Join-Path -Path (Split-Path -Path “${Env:SMS_ADMIN_UI_PATH}” -ErrorAction Stop) -ChildPath “ConfigurationManager.psd1”
Import-Module $CMModulePath -ErrorAction Stop
$CMProvider = Get-PSDrive -PSProvider CMSite -Name $siteCode -ErrorAction Stop
CD “$($CMProvider.SiteCode):\”
$global:CMProvider = $CMProvider
return $CMProvider
}
$CM = GetCMSiteConnection -siteCode $siteCode
$Info = Import-CSV $FilePath
ForEach ($File in $Info)
{
#$ColName = $File.CollectionName
#$Host = $File.HostName
try {
Add-CMDeviceCollectionDirectMembershipRule -CollectionName $File.CollectionName -ResourceId (Get-CMDevice -Name $File.HostName).ResourceID
Write-Host $File.HostName “successfully added in collection – ” $File.CollectionName -ForegroundColor Green
}
Catch {
$errormsg = $_.Exception.Message
Write-Host $File.Hostname “$errormsg For the Collection – ” $File.CollectionName -ForegroundColor Red
}
}
No response hence closing the thread.
Get the resource ID for each machine in a column, get the collection ID for collections and place them in two different columns , use the concatenate formula in excel to get the command according to below and run it in powershell by directly copy and paste all rows in once.
Add-CMDeviceCollectionDirectMembershipRule -CollectionId “SC100056” -ResourceId 2097152004