Move AD user by Powershell

Marc 631 Reputation points
2022-10-26T10:07:31.31+00:00

I have often move AD users from one OU to another OU.
I am trying to do that by powershell.
In doing that I have to inherit/replace the Meberof list and change the HomeDrive & ScriptPath.
Could you please give me some suggestions or a script to work on?
Thanks

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,382 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,096 Reputation points
    2022-10-27T01:48:43.8+00:00

    I don't know, and you don't say, what to do if there's not a populated HomeFolder property. My best guess would be something like this:

    $DefaultHomeFolderLocation = '\\disk1\homefolder'  
      
    $u = Get-ADUser -Id useracct -properties HomeDirectory  
    if ($u.HomeDirectory){  
        $newHomeFolderPath = "$(Split-Path $u.HomeDirectory -Parent)" + "\$userName"  
    }  
    else{  
        $newHomeFolderPath = $DefaultHomeFolderLocation + "\$userName"  
    }  
    
    0 comments No comments

7 additional answers

Sort by: Most helpful
  1. Andreas Baumgarten 97,396 Reputation points MVP
    2022-10-26T10:19:58.77+00:00
    0 comments No comments

  2. Marc 631 Reputation points
    2022-10-26T11:29:32.92+00:00

    Thank you @Andreas Baumgarten ,

    what about change the HomeDrive & ScriptPath related with the referiments of the new OU group?


  3. Marc 631 Reputation points
    2022-10-26T12:12:51.003+00:00

    I have found some cmdlets below:

    -----MOVE USER ------

    Get-ADUser -Identity Name.Surname | Move-ADObject -TargetPath "OU=HR,DC=SHELLPRO,DC=LOCAL"  
    

    If I have a target user (target OU) how can get the cleaned target path (without CN=)?

    ----DELETE "MEMBEROF" WORKING -----

    $Users =get-ADuser -identity John -properties *  
    ForEach($User In $Users){  
        $MemberOf = $User.MemberOf  
        ForEach($Group In $MemberOf){  
            Write-Host Removing $User from $Group  
            Remove-ADGroupMember $Group $User -Confirm:$false  
                }  
    }  
    
    0 comments No comments

  4. Rich Matheisen 45,096 Reputation points
    2022-10-26T14:52:15.283+00:00

    You can remove the CN from the distinguishedName like this:

    $dn = "CN=MySurname\, MyGivenname,OU=XXX,OU=YYY,DC=contso,DC=com"  
      
    $regex = 'CN=.*?(?<!\\),(.*)'  
      
    $DnMinusTheCN = $dn -replace $regex,'$1' # remove the CN from the DN  
    
    0 comments No comments