How do I set up a PowerShell script adding AD groups to PCs/user accounts in domain?

Below is what I have scripted (purpose if to add AD groups to specified parameters--computer name and username). I have a separate AD module script that is imported successfully. But the script below does not work. A colleague mentioned I needed to make reference to our company's domain. I added info such as the below (LDAP info, but just placeholder info there now). What else is needed to ensure this works with our AD domain environment?

[ADSI] "LDAP://cn=VPNAdminUsers,ou=West,dc=MyDomain,dc=com

function Add-DevADGroup {

try {
    param (
        [Parameter(Mandatory = $True)]
        [string] $ComputerName,
        [Parameter(Mandatory = $True)]
        [string] $UserName

[string]$LocalAdmin = (Get-ADGroup -Identity [ADSI] "LDAP://cn=GPP Computer Local Admin Exception,ou=West,dc=MyDomain,dc=com").DistinguishedName
[string]$RDP = (Get-ADGroup -Identity [ADSI] "LDAP://cn=GPP Computer RDP,ou=West,dc=MyDomain,dc=com").DistinguishedName
[string]$RDPException = (Get-ADGroup -Identity [ADSI] "LDAP://cn=GPP Computer RDP Exception,ou=West,dc=MyDomain,dc=com").DistinguishedName
[string]$VPNAdminUsers = (Get-ADGroup -Identity [ADSI] "LDAP://cn=VPNAdminUsers,ou=West,dc=MyDomain,dc=com").DistinguishedName

    $ADGroups = @()

foreach ($group in $ADGroups){
            Add-ADPrincipalGroupMembership -Identity $ADGroups -Members $ComputerName
            Write-Output ("{0} has been added to {1}" -f $group.Name, $ComputerName)

if ($ComputerName.Substring($ComputerName.Length -1) -match "L") {
            Add-ADGroupMember -Identity $VPNAdminUsers -Members $UserName
            Write-Output ("VPNAdminUsers has been added to {0}" -f $UserName)

    Catch {

    Write-Error "Unable to add all members to the specified AD Group(s)." -verbose



1 answer

  • answered 2018-12-05 20:49 Gabriel Luci

    If it needs to work in your environment, then the best way to test is to run it in your environment. Most PowerShell cmdlets have a -WhatIf parameter to tell it to make sure it would work but not actually change anything. So, for testing, you can add that to any cmdlet that would normally change something. For example:

    Add-ADPrincipalGroupMembership -Identity $ADGroups -Members $ComputerName -WhatIf

    Then once the script runs without errors, you can remove the -WhatIf and run it for real.

    That said, I can tell you that you have at least a couple syntax errors that would prevent this from running at all:

    1. You're missing a closing quote on the first line, and
    2. You're missing a } before Catch (it looks like one of the ones below the Catch block should be moved up)