Powershell – Creating users from a csv file in PowerShell

powershell

It's my first time in PowerShell to create users from a csv file. I am using a code from a tutorial I've watched, it's working on the when demonstrated on the video but, I can't make it work..

$ou=[ADSI] "LDAP:/..."
$dataSource = import-csv ".."

foreach($dataRecord in $dataSource) 
{

  $cn = $dataRecord.cn
  $sAMAccountName = $dataRecord.sAMAccountName
  $givenName = $dataRecord.FirstName
  $sn = $dataRecord.LastName
  $displayName = $sn + ", " + $givenName
  $userPrincipalName = $givenName + "." + $sn + "@nuggetlab.com"
  $newUser =  $ou.Create("user", "cn=" + $cn)

  $newUser.Put("sAMAccountName", $sAMAccountName)
  $newUser.Put("userPrincipalName", $userPrincipalName)
  $newUser.Put("displayName", $displayName)
  $newUser.Put("givenName", $givenName)
  $newUser.SetInfo()
  $newUser.SetPassword("Password")
  $newUser.psbase.InvokeSet("AccountDisabled", $false)
  $newUser.Put("company", "The Fantastic Four")
  $newUser.SetInfo()
}

The error says:

Exception calling "SetInfo" with "0" arguments(s): "The specified directory service or value does not exist"
At C:\Users\Administrator\Documents\CreateGroup.ps1:18 char18
+   $newUser.SetInfo <<<< ()
  + CategoryInfo          : NotSpecified: (:) [], MehthodInvocationException
  + FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI

Best Answer

$ou=[ADSI] "LDAP:/..."
$dataSource = import-csv ".."

foreach($dataRecord in $dataSource) 
{

  $cn = $dataRecord.cn
  $sAMAccountName = $dataRecord.sAMAccountName
  $givenName = $dataRecord.FirstName
  $sn = $dataRecord.LastName
  $displayName = $sn + ", " + $givenName
  $userPrincipalName = $givenName + "." + $sn + "@nuggetlab.com"
  $newUser =  $ou.Create("user", "cn=" + $cn)

  $newUser.Put("sAMAccountName", $sAMAccountName)
  $newUser.Put("userPrincipalName", $userPrincipalName)
  $newUser.Put("displayName", $displayName)
  $newUser.Put("givenName", $givenName)
  $newUser.SetInfo()
  $newUser.SetPassword("Password")
  $newUser.psbase.InvokeSet("AccountDisabled", $false)
  $newUser.Put("company", "The Fantastic Four")
  $newUser.SetInfo()
}
Related Topic