delanguageRegister | Login
fingerprint

Login

call

Contact

help

Help

Active Directory: Add user to group

1 ratings
active directoryaddusermultiplegroupsassignlogging

What it does

Add user to multiple groups with this PowerShell Script. You need to import the ActiveDirectory PowerShell module. With the admins buddy automation tasks you could enable other people to do administrative tasks. You could also log the data in the logs in addy and on premise (your addy pod).

Description

Add an Active Directory User Account to one or more Active Directory Groups.

Creation Details

  • Author: Sebastian Renners
  • Created: 15.06.2022 13:14:45
  • Last modification: 15.06.2022 13:14:45
Resource Image:

Input Parameters

Name: adgroupsstring

Description: Type in a group or multiple groups, separated by a semicolon. For example: "group_1;group_2;group_3"

Name: aduser

Description: Type in a user (samaccountname).

Resource Parameters

No resource parameters set

Code

[CmdletBinding()]
Param(
    [Parameter(Mandatory=$false)]
    [string]$installPath="not-set",
    [Parameter(Mandatory=$false)]
    [string]$jobId="not-set",
    [Parameter(Mandatory=$false)]
    [string]$action="not-set"
)

$debugScript = 0;
if ($debugScript -eq 1) {
    $installPath = "C:\addy\" #Debugging
    $jobId = "jobXXX" #only for debugging
}
#Only use TLSv1.1 and TLSv1.2
$AllProtocols = [System.Net.SecurityProtocolType]'Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

$errorCount = 0 #counting errors. If this variable is greater than 0, the script should not run
$error.clear()
#loading functions #this is important!
write-host "$(get-date -f  "dd.MM.yyyy HH:mm:ss") include functions"
if (test-path "$($installPath)scripts\functions.global.ps1") {
    write-host "Functions-File exists"
    import-module "$($installPath)scripts\functions.global.ps1" -force
} else {
    write-host "Functions-File do not exist. Increasing ErrorCounter." 
    $errorCount++
}

#setting the location
set-location $installPath

#generate a unique machineID #this is important
$machineId = Get-MachineId
  
#write a log online and offline
if ($debugScript -eq 0) {
    write-addylog "All parameter initialized"
}

#####Handling with parameters
if ($debugScript -eq 0) {
    ### Load parameter information about this job
    $jsonBody = @{ localCurrentTime = $(get-date -f  "dd.MM.yyyy HH:mm:ss")}
    $body = (ConvertTo-Json -Depth 4 $jsonBody) 
    $resultInitializeInvoke = Invoke-RestMethod -Uri "$addyhostaddress/api/v1/heartbeat-consumer?action=checkforjobs&jobId=$jobId" -Method POST -Body $body -ContentType 'application/json; charset=UTF-8' -Headers @{"Publickey"="$publickey";"Privatekey"="$privatekey";"Machineid" = "$machineId"}
}
###################### YOUR SCRIPT STARTS HERE ############################
write-addylog "Start the Script." #-Level "INFO","ERROR", "WARN"

write-addylog "Initializing input parameter"
$addyPayloadResourceInput = $resultInitializeInvoke.jobDataArray.businessAutomationJobsPendingPayload.payload

$adGroupsString = $addyPayloadResourceInput.adgroupsstring #"adgroupsstring" is definied in the Resource input Parameter. This are now a parameter for this script 
$adUser = $addyPayloadResourceInput.aduser #"aduser" is definied in the Resource input Parameter. This are now a parameter for this script 


write-host "Initialize the variables"

write-addylog "adGroupsString is set to: $adGroupsString" #input parameter
write-addylog "adUser is set to: $adUser" #input parameter

start-sleep 1

write-addylog "Loading the ActiveDirectory Module"

if (Get-Module -ListAvailable -Name ActiveDirectory) {
    write-addylog "Module ActiveDirectory exists"
} 
else {
    write-addylog "Module ActiveDirectorydoes not exist"
    write-addylog "Please load the active directory module first"
    Import-Module -Name ActiveDirectory
    $errorCount++
}

start-sleep 1
if ($errorCount -eq 0) {
    # check the parameters
    if ($adUser -eq "") {
        write-addylog "Parameter `$adUser can not be empty" -level ERROR
        $errorCount++;
    }
    if ($adGroupsString -eq "") {
        write-addylog "Parameter `$adGroupsString can not be empty" -level ERROR
        $errorCount++;
    }
    if ($TicketNumber -eq "") {
        write-addylog "Parameter `$TicketNumber can not be empty" -level ERROR
        $errorCount++;
    }
} #if ($errorCount -eq 0) {

if ($errorCount -eq 0) {
    #some checks for the lengt. Edit this length for your environment
    if ($adUser.Length -lt 3) {
        write-addylog "Parameter lenght of `$adUser unvalid" -level ERROR
        $errorCount++; 
    }
    if ($adGroupsString.Length -lt 5) {
        write-addylog "Parameter lenght of `$adGroupsString unvalid" -level ERROR
        $errorCount++; 
    }
} #if ($errorCount -eq 0) {

if ($errorCount -eq 0) {
    #check if user exists
    $UserExists = $false
    try {
        $adUserData = Get-ADUser -Identity $adUser #check if you need to import the Module ActiveDirectory
        $UserExists = $true
    }
    catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException] {
        write-addylog "Given user does not exist in Active Directory" -level ERROR
        $UserExists = $false
        $errorCount++
    }
    write-host "`$UserExists: $UserExists"

} #if ($errorCount -eq 0) {

if ($errorCount -eq 0) {
    $adUserData = get-aduser -Identity $adUser -Properties mail,info | select-object * 

    #split the groups to array elements
    $adGroupsArray = $adGroupsString.Split(";")
    $adGroupsArray = $adGroupsArray.Where({ $_ -ne "" }) #remove empty array elements

    $countSuccess = 0;
    foreach($adGroupElement in $adGroupsArray){ 

        #check if group exists
        $GroupExists = $false
        try {
            $GetAdGroup = Get-ADGroup -Identity $adGroupElement
            $GroupExists = $true
        }
        catch [Microsoft.ActiveDirectory.Management.ADIdentityResolutionException] {
            #Write-Host "[$adGroupElement] Given group does not exist in Active Directory" -f red
            $GroupExists = $false
        }

        if ($GroupExists -eq $true) {
            write-addylog "[$adGroupElement] Group exist"
            $GetAdGroup
            start-sleep 2

            Add-ADGroupMember -Identity $adGroupElement -Members $adUserData.SamAccountName
            write-addylog "[$adGroupElement] Adding Group $adGroupElement to user account $($adUserData.SamAccountName)"
            $countSuccess++
        } else {
            write-addylog "[$adGroupElement] Given group does not exist in Active Directory" -level WARN
        } # if ($roupExists -eq $true) {...} else {}

    } #foreach($adGroupElement in $adGroupsArray){
        
    if ($countSuccess -gt 0) {
        write-addylog "User Account successfully assigned to $countSuccess of $($adGroupsArray.count) Group(s)."

    } else {
        write-addylog "Group assigment not successfull. Please check the logs!" -level WARN
    }

} #if ($errorCount -eq 0) {
else {
    write-addylog "Some errors occured. Group assigment failed." -level ERROR
}

###################### YOUR SCRIPT ENDS HERE ############################
#setting the state #this is important!
if ($debugScript -eq 0) {
    write-addylog "update state of this job to done"
    update-modifiedState -jobId $jobId -modifiedState "done" -publickey $publickey -privatekey $privatekey -machineId $machineId
    Start-Sleep 5 
    write-addylog "End of script reached" 
    Start-Sleep 1
    exit
}

Rating

login and obtain the library resource to set a rating.