Powershell - Add Users / Computers to AD Group

The below script can be used to add multiple user or computer to an AD group. The list of users / computers to be provided in the text file.

Usage: See below example. To see full help Type script name and press enter. You have to provide computer name or user name (SAM Account) in text file.


Add computer to AD Group
    .\AddObjectsToADGroup.ps1 -FileName Computers.txt -ADGroupName "TestGroup" -ObjectType Computer

.Add user to AD group
    .\AddObjectsToADGroup.ps1 -FileName Computers.txt -ADGroupName "TestGroup" -ObjectType User

Github Repostiorty


Raw File

#Script

#Version: 1.0
#Author: Equebal Ahmad

<#
.SYNOPSIS
    Add the computers / users account to an AD Group
.DESCRIPTION
    Add the computers / users account to an AD Group

    The script can add user and computer in an AD group. You need to pass this with ObjectType parameter.
.EXAMPLE
    .\AddObjectsToADGroup.ps1 -FileName Computers.txt -ADGroupName "TestGroup" -ObjectType Computer
.EXAMPLE
    .\AddObjectsToADGroup.ps1 -FileName Computers.txt -ADGroupName "TestGroup" -ObjectType User

.NOTES
    None
.PARAMETER FileName
    Provide the name of text file with list of computers / users to be added to AD Group
.PARAMETER ADGroupName
    Name of AD group where computers / users to be added
.PARAMETER ObjectType
    The ObjectType can be either computer or user. Any other parameter will not accepted.
    
#>  


[CmdletBinding()]
Param(
  [Parameter(Mandatory=$True)]
   [string]$FileName,
   [Parameter(Mandatory=$True)]
   [string]$ADGroupName,

   [Parameter(Mandatory=$True)]
   [ValidateSet('Computer','User')]
   [string]$ObjectType

)


#Import modules
Import-Module ActiveDirectory

#Delcare variables
$TargetGroup = Get-ADGroup -Filter {Name -eq $ADGroupName} 
$TargetGroup

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$input = $directorypath + "\" + $FileName

if($ObjectType -eq "Computer"){
    Get-Content $input | ForEach-Object{
    $computer = Get-ADComputer  $_
    Add-ADGroupMember  -identity $TargetGroup -Members $computer.DistinguishedName}}
else{
    Get-Content $input | ForEach-Object {
    $User = Get-ADUser $_
    Add-ADGroupMember -Identity $TargetGroup -Members $User.DistinguishedName}}  

Comments

Popular posts from this blog

SCCM Software Distribution Troubleshooting

Powershell - List AD Organizational Unit and GPOs linked to them

Troubleshooting System Center Endpoint Protection (SCEP) Client