I am currently working on an assignment for class, where we need to use the Dsadd command in order to import a list of CSV users into Active Directory.
This is my script:
$CSV = Import-Csv -Delimiter "," -Path "$PWD\TestCSV.csv"
foreach ($user in $CSV)
{
$Member = $User.Title + ","
$Domain = $User.Domain + ", DC=Domains" + ", DC=com" + "`""
$Name = $User.Firstname + " " + $User.Lastname + ","
$Password = $User.Password
write-host Dsadd user `"CN=$Name"" DC=$Domain -pwd $User.Password -memberof `"CN=$Member" CN=Users, DC=$Domain"
}
When I execute it, it prints the following to the powershell window:
Dsadd user "CN=Abruaba Rodriguez, DC=CoolDomain, DC=Domains, DC=Com" -pwd password
-memberof "CN=gk_students, CN=Users, DC=CoolDomain, DC=Domains, DC=com"
This is the correct syntax to add a user with that name, as if I invoke that line by itself, it works. But if I remove write-host the command fails saying "dsadd failed:'DC=Domains,' is an unknown parameter.
Any advice? Thanks in advance.
EDIT: I got my script to work through a workaround, however I dont think it is the best way this script could be run.
I changed the last line and added two more. Instead of writing to the host, I wrote-out to a variable and then put that output on a single line. Then I simply invoked the variable and success! it worked:
$Execute = write-output Dsadd user `"CN=$Name"" DC=$Domain -pwd $User.Password -memberof `"CN=$Member" CN=Users, DC=$Domain"
$Fields="{0} {1} {2} {3} {4} {5} {6} {7}" -f $Execute
Invoke-Expression $Fields
Is there a better way to do this task with powershell?