We're trying to bulk-create users on a Windows 2012 Server system; the system is only intended to allow us to validate an ALM solution and it will be extremely short lived, which means we do not care for now for security. When running the script below, the shell reports Exception calling "SetInfo" with "0" argument(s): "The specified username is invalid." for each line in the input file. However, if we manually execute the lines inside the loop, the user is properly created.
# Work on the local system
$Computer =[ADSI]"WinNT://$env:ComputerName,Computer"
$UsersFilePath = "C:\users\Administrator\Downloads\ActiveUsers.txt"
$Group=[ADSI]"WinNT://WORKGROUP/./Developers,Group"
Get-Content $UsersFilePath | % {
$_ # Debug only line, remove it when done
$LocalUser=$Computer.Create("User", $_ )
$LocalUser.SetPassword( $_ )
$LocalUser # Debug only line, remove it when done
$LocalUser.SetInfo()
}
How should we write the loop?
[Here is the answer, as suggested by mjolinor; the main change is the trimming of the name read from the file]
# Work on the local system
$Computer =[ADSI]"WinNT://$env:ComputerName,Computer"
$UsersFilePath = "C:\users\Administrator\Downloads\ActiveUsers1.txt"
$Group=[ADSI]"WinNT://WORKGROUP/./Developers,Group"
Get-Content $UsersFilePath | % {
$_ # Debug only line, remove it when done
$UserName = $_.Trim()
$LocalUser=$Computer.Create("User", $UserName)
$LocalUser.SetPassword( $UserName )
#$LocalUser.put("userPrincipalName", "${name}@svr-tfs2013" )
$LocalUser # Debug only line, remove it when done
$LocalUser.SetInfo()
$Group.Add($LocalUser.path)
}
Putmethod withSetInfoe.g.$localUser.Put("userPrincipalName", "${name}@$domain"); $localUser.SetInfo()or maybe you need to put theSAMAccountNameas well?