I'm writing a Powershell script to create a user account in Active Directory, and I want to use credentials to do it, so I am using .NET
$objDirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry ($OU,$($Credential.UserName),$($Credential.GetNetworkCredential().password))
$Account = $objDirectoryEntry.psbase.get_children().add("CN="+$AccountName,"User")
$Account.psbase.InvokeSet("sAMAccountName",$sAMAccountName)
$Account.psbase.invokeset("DisplayName", $Displayname)
$Account.psbase.invokeset("Description", $Description)
$Account.psbase.CommitChanges()
it seems impossible to set the infamous 'UserAccountControl' parameter
$Account.psbase.invokeset(“userAccountControl”, 66048) #fails
$Account.psbase.invokeset(“userAccountControl”, 0x10200) #fails
$Account.psbase.invokeset(“userAccountControl”, 0x2) #fails
On the other hand using the ADSI wrapper works fine.
$objADSI = [ADSI]$AdminOU
$objAccount = $objADSI.create("User","CN="+$AccountName)
# Create the account
$objAccount.put("SamAccountName", $AccountName)
$objAccount.put("DisplayName", $Displayname)
$objAccount.put("Description", $Description)
$objAccount.SetInfo()
# set password
$objAccount.SetPassword($AdminAccountPassword)
$objAccount.SetInfo()
# set the userAccountControl
$objAccount.put(“userAccountControl”, 66048)
$objAccount.SetInfo()
But cannot get ADSI wrapper method to run under different credentials.
Spend way too much time banging my head on this one, the only other methods I can think of is to start save the ADSI method to a external script and invoke it using credentials, surely theres a way
I found an easy way to get credentials into the powershell ADSI wrapper.
$objADSI = [ADSI]$LDAPPath
$objADSI.PsBase.Username = $UserName
$objADSI.PsBase.Password = $Password
Use psbase to expose hidden attributes of System.DirectoryServices.DirectoryEntry .NET object
You can then return to the usual powershell ADSI wrapper methods and it all works well.