Splitting EmployeeID then add membership by split employeeID variables

David Thomas 1 Reputation point
2022-10-25T07:01:01.377+00:00

Hi All,
I am still kind of new to PS and was banging my head against a wall with this one...
I am having issues trying to assign users to groups listed in a csv, like this
TestGroup1 TestGroup2
9000 9001
9001 9003
9002
9003

And the EmployeeID Attribute looks like this
Test.1 9000
Test.2 9001 9002
Test.3 9003 9000
Test.4 9003
The Idea here is that while a staff member is acting manager for example they will continue to have access to the groups they normally require and also the additional EmployeeID group access
End Goal would look like this
TestGroup1 Membership
Test.1
Test.2
Test.3
Test.4
TestGroup2 Membership
Test.2
Test.3
Test.4

When I run the Script below
Only Test.1 and Test.4 populate to TestGroup1 and only Test.4 Populates in TestGroup2
Missing the EMployeeID attribute with 9 characters

$csv = import-csv -path "C:\Script\Working Scripts\DynamicDistributionGroup.csv"
$gm = ( $csv |Get-Member)
$gmC = $gm.Count - 1
$cols = $gm[4..$gmC]
foreach ($c in $cols) {
Write-Host = $c.Name
$colName = $c.Name
ForEach-Object {Get-AdGroupmember "$ColName"} | ForEach-Object {Remove-ADGroupMember "$colName" $_ -Confirm:$false}

ForEach-Object {$DistributionGroup = "CN=$ColName,(HaveRemovedThisForPrivacy)"  
  

foreach($line in $csv){
$EmpID = ($line.$ColName)
$Length = $EmpID.Length
$Users = Get-ADUser -SearchBase "OU=Testing,(HaveRemovedThisForPrivacy)" -Filter * -Properties EmployeeID,Enabled | Where-Object {$.Enabled -eq $True} | Select-Object sAMAccountName
if ($EmpID.length -gt 0) {
if ($EmpID.Length -lt 5) {
$EmpIDFirst4 = $EmpID.Substring(0, 4);
$Users = Get-ADUser -SearchBase "OU=Testing,(HaveRemovedThisForPrivacy)" -Filter * -Properties EmployeeID,Enabled | Where-Object {$
.EmployeeID -contains "$EmpIDFirst4" -and $.Enabled -eq $True} | Select-Object sAMAccountName
foreach ($User in $Users){
Add-ADGroupMember -Identity $DistributionGroup -Members $Users
} write-host $Users And $EmpIDFirst4
}else {
$EmpID2ndFirst4 = $EmpID.Substring(0, 4);
$EmpIDLast4 = $EmpID.Substring($EmpID.length -4);
$Users = Get-ADUser -SearchBase "OU=Testing,(HaveRemovedThisForPrivacy)" -Filter * -Properties EmployeeID,Enabled | Where-Object {$
.EmployeeID -contains "$EmpIDLast4" -or $.EmployeeID -contains "$EmpID2ndFirst4" -and $.Enabled -eq $True} | Select-Object sAMAccountName
foreach ($User in $Users){
Add-ADGroupMember -Identity $DistributionGroup -Members $Users
} write-host $EmpIDLast4 And $Users

    }  
}   
}  

}
}

Active Directory
Active Directory
A set of directory-based technologies included in Windows Server.
6,523 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,521 questions
0 comments No comments
{count} votes

4 answers

Sort by: Most helpful
  1. David Thomas 1 Reputation point
    2022-10-25T07:06:13.963+00:00

    253772-dynamicgroupbyemployeeid.txt

    Sorry Script got hit by formatting.....gah


  2. Rich Matheisen 46,711 Reputation points
    2022-10-25T15:24:08.647+00:00

    I tidied up the code a bit, and added comments where I think you either used the wrong variable name, used quotes where they aren't needed and, more importantly, used "Select-Object" in a way that's incompatible with the code. The "Select-Object" using the -Property parameter results in a PSCustomItem with properties named the same as the property names that follow the -Property parameter. In your script you're using the PSCustomObject as if it's a string value. In other words, you should be using, for example, "$User.sAMAccountName" where you've used "$User". By using the "-Expand" parameter of the Select-Object, you'll get just the value of the single property.

    Anyway, here's the code.

    $csv = Import-Csv -Path "C:\Script\Working Scripts\DynamicDistributionGroup.csv"  
    $gm = ( $csv | Get-Member)  
    $gmC = $gm.Count - 1  
    $cols = $gm[4..$gmC]  
    foreach ($c in $cols) {  
        Write-Host = $c.Name  
        $colName = $c.Name  
        ForEach-Object { Get-ADGroupMember "$ColName" } |   
            ForEach-Object { Remove-ADGroupMember "$colName" $_ -Confirm:$false }  
              
        ForEach-Object { $DistributionGroup = "CN=$ColName,(HaveRemovedThisForPrivacy)"  
      
            foreach ($line in $csv) {  
                $EmpID = ($line.$ColName)  
                $Length = $EmpID.Length  
                $Users = Get-ADUser -SearchBase "OU=Testing,(HaveRemovedThisForPrivacy)" -Filter * -Properties EmployeeID, Enabled |   
                    Where-Object { $_.Enabled -eq $True } |     # NO NEED FOR THE "-eq $true"  
                        Select-Object sAMAccountName  
                if ($EmpID.length -gt 0) {  
                    if ($EmpID.Length -lt 5) {  
                        $EmpIDFirst4 = $EmpID.Substring(0, 4)   # WHAT HAPPENS HERE IF THE STRING CONTAINS FEWER THAN 4 CHARACTERS????  
                        $Users = Get-ADUser -SearchBase "OU=Testing,(HaveRemovedThisForPrivacy)" -Filter * -Properties EmployeeID, Enabled |   
                            Where-Object { $_.EmployeeID -Contains "$EmpIDFirst4" -and $_.Enabled -EQ $True } |  # NO NEED FOR THE QUOTES OR THE "-EQ $True"  
                                Select-Object sAMAccountName    # PROBABLY NOT WHAT YOU WANT: USE "-ExpandProperty sAMAccountName"  
                        foreach ($User in $Users) {  
                            Add-ADGroupMember -Identity $DistributionGroup -Members $Users  # YOU'VE USED $Users WHEN YOU SHOULD USE $user  
                        }   
                        Write-Host $Users And $EmpIDFirst4  
                    }  
                    else {  
                        $EmpID2ndFirst4 = $EmpID.Substring(0, 4);  
                        $EmpIDLast4 = $EmpID.Substring($EmpID.length - 4);  
                        $Users = Get-ADUser -SearchBase "OU=Testing,(HaveRemovedThisForPrivacy)" -Filter * -Properties EmployeeID, Enabled |   
                            Where-Object { $_.EmployeeID -Contains "$EmpIDLast4" -or $_.EmployeeID -Contains "$EmpID2ndFirst4" -and $_.Enabled -EQ $True } |    # NO NEED FOR THE QUOTES OR THE "-EQ $True"   
                                Select-Object sAMAccountName    # PROBABLY NOT WHAT YOU WANT: USE "-ExpandProperty sAMAccountName"  
                        foreach ($User in $Users) {  
                            Add-ADGroupMember -Identity $DistributionGroup -Members $Users  # YOU'VE USED $Users WHEN YOU SHOULD USE $user  
                        }   
                        Write-Host $EmpIDLast4 And $Users  
      
                    }  
                }   
            }  
        }  
    }  
    

  3. David Thomas 1 Reputation point
    2022-10-26T03:49:44.18+00:00

    Oh Geez, this whole thing is about face, i should be testing the employeeid AD attribute not the csv......

    0 comments No comments

  4. David Thomas 1 Reputation point
    2022-11-03T23:10:17.6+00:00

    Ok after many forehead smacks, I've finally got something that I believe works for what I wanted to achieve!!! YAY!!! This will only work for EmployeeID's that are 4 characters long and seperated by a space in your active directory, if you use different lengths you would need to adjust accordingly, also only works for 2 different employee numbers, if you need more you would need to add more IF statements and increment your index's. Let me know if this helps any of you guys!!! I now hope to implement this script for all my group memberships and maintain a user access matrix based on employeeID.

    <#Set Variables#>  
        $csv = Import-Csv -Path "C:\Script\Working Scripts\DynamicDistributionGroup.csv"  
        $gm = ( $csv | Get-Member)  
        $gmC = $gm.Count - 1  
        $cols = $gm[4..$gmC]  
        $Users = Get-ADUser -SearchBase "OU=Testing,OU=(Hidden),DC=(hidden),DC=local" -Filter *  -Properties employeeID, displayName, userPrincipalName      
        <#Create User Array from Active Directory#>  
        $x = @()  
        ForEach ($user in $Users){  
            $x += [PSCustomObject]@{  
                SamAccountName = $User.sAMAccountName  
                EmployeeID = $User.EmployeeID  
            }  
        }  
        <#Get Group Names from Csv#>  
        foreach ($c in $cols) {  
            Write-Host = $c.Name  
            $colName = $c.Name  
            <#Remove all Group Members of Each Group#>  
            ForEach-Object {Get-AdGroupmember "$ColName"} | ForEach-Object {Remove-ADGroupMember "$colName" $_ -Confirm:$false}  
            <#Do for Each Group#>  
            ForEach-Object {$DistributionGroup = "CN=$ColName,OU=(Hidden),OU=(Hidden),OU=(Hidden),DC=(Hidden),DC=local"     
            <#Create Cell Array for each Column in Csv#>  
            $y = @()  
            foreach($line in $csv) {  
                $y += [PSCustomObject]@{  
                    Cell = $line.$ColName  
                }  
            }  
            <#Get User from User Array and do for each User#>  
            foreach ($User in $x) {  
                <#Test if AD EmployeeID attribute not equals null#>  
                if ($User.EmployeeID.Length -gt 0) {  
                    <#Test if AD EmployeeID attribute equals 4 characters#>  
                    if ($User.EmployeeID.Length -eq 4) {  
                        <#Does Cell Array contain User AD EmployeeID Attribute?#>  
                        if ($y.Cell -contains $User.EmployeeID) {  
                                <#Add to Each Group#>  
                                Add-ADGroupMember -Identity $DistributionGroup -Members $User  
                        }  
                    } else {  
                        <#Test if AD EmployeeID attribute equals 9 characters#>  
                        if($user.EmployeeID.Length -eq 9){  
                            <#Split EmployeeID attribute by space#>  
                            $SplitEMPID = $User.EmployeeID.Split(" ")  
                            <#Does Cell Array contain User AD EmployeeID Attribute for index 0 (First index)#>  
                            if ($y.Cell -contains $SplitEMPID[0]) {  
                                Add-ADGroupMember -Identity $DistributionGroup -Members $User  
                            } else {  
                                <#Does Cell Array contain User AD EmployeeID Attribute for index 1 (Second index)#>  
                                if ($y.Cell -contains $SplitEMPID[1]) {  
                                    Add-ADGroupMember -Identity $DistributionGroup -Members $User  
                                }  
                            }  
                        }  
                    }  
                }  
            }      
            }  
        }  
          
      
      
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.