Search code examples
csvpowershell-3.0adgroup

How to update AD Info attribute to list groups user was deleted from?


I have this script that will only list a user's groups on the ISE screen where the data can be copied and pasted elsewhere, but I'm trying to get the group membership names written into the Telephone Notes tab (or Info field). I'm thinking next that these probably need to be turned into string values since I'm getting errors about multi properties not allowed. Here is what I've been trying, but I keep getting errors. Thanks

Import-Module ActiveDirectory

$Users= Import-csv "C:\Scripts\UsersSAM-DisplayName.csv" 
ForEach ($User in $Users) {
   $SamAccountName=$User.SamAccountName
   $DisplayName=$User.DisplayName
   $TableFormat= @{E={$_.Name};L="$($DisplayName) - $($SamAccountName)"}
Get-ADUser -Identity $SamAccountName -Properties MemberOf | % {$_.MemberOf } | % {Get-ADGroup -Identity $_ } | % { Set-ADUser -Identity $SamAccountName -add @{info="$_.name"}} | Select Name |
Format-Table $TableFormat }

Solution

  • I figured this out. What they wanted was to first write out a terminated user's groups, then remove those. I did it like this and this code includes the semi-colon so if the user comes back, all you need to do to add them back to all the groups is copy and paste those from the output stored in the Telephones Tab, Notes field. I've also used a trimmed down version of this to export a user's groups to speed up duplicating a user's groups so they match with others on the same team. Hope this helps someone.

    Import-csv "$Terms" | % {
      $user = Get-ADUser -LDAPFilter ("(sAMAccountName=" + $_.samaccountname + ")") -Properties samaccountname,enabled,name,memberof,distinguishedname,info 
    
    #Grab all user group names
      $user | ForEach-Object {
        $grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
        $arec = $_.Name,$_.SamAccountName
        $aline = ($grps -join ";")  
    
    #Add info to Notes field Telephone Tab    
      Get-ADPrincipalGroupMembership -Identity $user | %{
        If ($_.SamAccountName -ne "Domain Users") {
        $Userinfo=$user.info
        Set-ADUser $User -replace @{info= "$Userinfo | $a | Terminated via automated process | $aline"}
    
    #Remove User Groups Process in Telephones Tab Notes Field.
        Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_.SamAccountName -Confirm:$false 
         ("  "+ $a +" [" + $User.samaccountname + "], Removed from group [" + $_.samaccountname + "]. ") | Out-File -FilePath $ErrorLog -Append
      }
      }}}