Author Posts

November 14, 2014 at 6:12 am

I am quite new at this. Getting some errors. First here is my code

$objOU=[ADSI]“thisismydomain://OU=This,OU=Is,DC=My,DC=Domain”
$dataSource=import-csv “c:\\users.csv”
foreach($dataRecord in $datasource) {

$cn=$dataRecord.FirstName + ” ” + $dataRecord.LastName
$sAMAccountName=$dataRecord.FirstName # + “.” + $dataRecord.LastName
$givenName=$dataRecord.FirstName
$description=$dataRecord.Description
$sn=$dataRecord.LastName
$sAMAccountName=$sAMAccountName.ToLower()
$displayName=$sn + “, ” + $givenName
$userPrincipalName=$sAMAccountName + “@mydomain.mine”

$objUser=$objOU.Create(“user”,”CN=”+$cn)
$objUser.Put(“sAMAccountName”,$sAMAccountName)
$objUser.Put(“userPrincipalName”,$userPrincipalName)
$objUser.Put(“displayName”,$displayName)
$objUser.Put(“givenName”,$givenName)
$objUser.Put(“sn”,$sn)
$objUser.Put("description",$description)
$objUser.SetInfo()
$objUser.SetPassword(“micro33”)
$objUser.psbase.InvokeSet(“AccountDisabled”,$false)
$objUser.SetInfo()
Read-Host -Prompt "Press Enter to exit"
}

[u][b]I"m not sure where I'm going wrong[/b][/u]

Here is the error.

The following exception occurred while retrieving member "Create": "Unknown error (0x80005000)"
At C:\PSUsersScript.ps1:14 char:10
+ $objUser= <<<< $objOU.Create("user","CN="+$cn) + CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException + FullyQualifiedErrorId : CatchFromBaseGetMember You cannot call a method on a null-valued expression. At C:\PSUsersScript.ps1:17 char:13 + $objUser.Put <<<< ("displayName",$displayName) + CategoryInfo : InvalidOperation: (Put:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. Any ideas?

November 14, 2014 at 6:22 am

That error indicates that $objUser does not contain an object. Either your Create() failed, or $objUser was not set to a reference of an object. The first error suggests that Create() isn't working.

Consider setting a PSBreakpoint on the error line. That would let you suspend the script and check to see what $objUser actually contains.

All that said, using ADSI is kinda VBScript-old-school. Provided your DCs are at least Win2003, and at least one DC is running the AD Web Service Gateway (runs on 2003+, comes with 2008R2+), you can use Microsoft's ActiveDirectory module and its handy New-ADUser cmdlet. Much more straightforward. That cmdlet can be found in the RSAT, and in fact your script could probably be reduced to a single-line command.

As a style note, the world's more or less moved away from the Hungarian notation prefixes (e.g., "obj"). You'll usually see PowerShell variables named just $user or $OU or whatever. Not that you're wrong, just the other kids might snicker a bit :).