I'm writing a Powershell script to populate all the company users to a Active Directory from a CSV file.
The script uses the Powershell command New-ADUser
and it should know, for every user, where is the path to add them, for example:
"OU=IT Dept,OU=Users,DC=local,DC=contoso"
The problem is: this Active Directory doesn't have any users yet, so there's no Organizational Units created, and whenever I run the script, if the path doesn't exists, the user is not created.
I've looked up for a command to create Organizational Units, like New-ADOrganizationalUnit
or dsadd
, however they do not support recursive creations, like
"OU=Helpdesk,OU=IT Dept,OU=Users,DC=local,DC=contoso"
if
"OU=IT Dept,OU=Users,DC=local,DC=contoso"
does not exist yet.
Is there any way of doing that using New-ADOrganizationalUnit?
Thanks
As mentioned in the comments by Mike, you'll need to step through each level in the tree and test for the existence of the OUs ancestors, and then create the ones that doesn't exist, from the top-most level and down.
As long as
New-ADOrganisationalUnit
does not have a -Recurse parameter, this is the most elegant way I could think of:Usage using WHATIF
Without WHATIF
It will break if there are non-existing non-OU containers in the path.
The output of
$NextOU.IndexOf("OU=")
is case sensitive and will return -1 for all lowercaseou=
try:$NextOU.IndexOf("OU=",[StringComparison]"CurrentCultureIgnoreCase")
Try this approach; it is much simpler: https://dimitri.janczak.net/2016/04/20/recursive-ou-creation-with-powershell/