Friday, November 11, 2011

Powershell and Active Directory: Moving user to another OU

Given a username passed as a parameter to the script, the code below will find the specified user in AD and move to the specified OU


$UserName = $args[0]

$root=[ADSI]''

$searcher = new-object System.DirectoryServices.DirectorySearcher($root)

$searcher.filter = "(&(objectClass=user)(sAMAccountName= $UserName))"

$User = $searcher.findone()

# Binding the user account to $AUser and the OU to move to to $MovetoOU
Write-Host $User.Properties.adspath

$ADSPath = $User.Properties.adspath

$MoveToOU = [ADSI]("LDAP://OU=NewOU,DC=mydomain,DC=com")

$AUser = [ADSI]("$ADSPath")


# Command to Do the actual move
$AUser.PSBase.moveto($MoveToOU)

No comments:

Post a Comment