Hello all…
I am in the middle of writing a script to export my active directory (OU, user, computer, group) to a csv file and import it into another domain for some testing. I have been working on this all day, so I may be in the weeds instead of noticing the wide open field right in front of me - hopefully you can help.
A simplified version of my export script…
$ou = Get-ADOrganizationalUnit -Filter * | select -Property distinguishedName, name, SamAccountName # add some note property members so that all objects have the same properties $ou | Add-Member -MemberType NoteProperty -Name UserPrincipalName -Value OU $ou | Add-Member -MemberType NoteProperty -Name EmailAddress -Value OU $ou | Add-Member -MemberType NoteProperty -Name GroupScope -Value OU $ou | Add-Member -MemberType NoteProperty -Name ObjectType -Value OU $ou | Export-Csv -Path $objectFile -NoTypeInformation $user = Get-ADUser -Filter * -Properties * | select -Property distinguishedName, name, SamAccountName, UserPrincipalName, EmailAddress # add some note property members so that all objects have the same properties $user | Export-Csv -Path $objectFile -NoTypeInformation -Append $pc = Get-ADComputer -Filter * | select -Property distinguishedName, name, SamAccountName # add some note property members so that all objects have the same properties $pc | Export-Csv -Path $objectFile -NoTypeInformation -Append $group = Get-ADGroup -Filter * | select -Property distinguishedName, name, SamAccountName, GroupScope # add some note property members so that all objects have the same properties $group | Export-Csv -Path $objectFile -NoTypeInformation -Append
The above script exports a to a csv file the OUs, users, groups, and computers.
Now - for the import -
I prompt for a new domain name, and then find and replace all necessary instances of the production domain vs the lab domain. Then I import the csv file of all of the objects…
# add a script method to the objects object to count the number of commas in the dn field name # this allows me to sort on the number of commas in the DN so I (hopefully) create the OUs in the correct order - for nested OUs $objects | Add-Member -MemberType ScriptProperty -Name OULevel -Value {$this.distinguishedName -split "," | Measure-object | select -ExpandProperty Count} ### - here is where I am stuck ### $objects | Add-Member -MemberType ScriptMethod -Name BaseDN -Value {$i=$this.distinguishedName.IndexOf(","); $this.distinguishedName.SubString($i, $this.distinguishedName.Length - 1);}
That doesn’t seem to work. I keep getting “Exception Calling BaseDN with “0” arguments: Exception calling “Substring” with 2 arguments.: Index and length must refer to a location within the string”
What am I doing wrong?
Thanks in advance
sb