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 )

    0
    2020-09-01T05:22:33+05:30

    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
    }
    }

  1. No response hence closing the thread.

    0
    2020-08-18T13:52:52+05:30

    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

    Best answer

Leave an answer

Sorry, you do not have permission to answer to this question .