使用Powershell和.NET设置'UserAccountControl'

时间:2015-04-01 18:32:13

标签: .net powershell adsi

我正在编写Powershell脚本以在Active Directory中创建用户帐户,我想使用凭据来执行此操作,因此我使用的是.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()

似乎无法设置臭名昭着的UserAccountControl'参数

$Account.psbase.invokeset(“userAccountControl”, 66048) #fails
$Account.psbase.invokeset(“userAccountControl”, 0x10200) #fails
$Account.psbase.invokeset(“userAccountControl”, 0x2) #fails

另一方面,使用ADSI包装器工作正常。

$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()

但是不能让ADSI包装器方法在不同的凭据下运行。

花太多时间在我的头上敲打,我能想到的唯一其他方法是开始将ADSI方法保存到外部脚本并使用凭证调用它,当然这是一种方式

1 个答案:

答案 0 :(得分:2)

我找到了一种简单的方法来获取powershell ADSI包装器的凭据。

$objADSI = [ADSI]$LDAPPath
$objADSI.PsBase.Username = $UserName
$objADSI.PsBase.Password = $Password

使用 psbase 公开 System.DirectoryServices.DirectoryEntry .NET对象的隐藏属性

然后,您可以返回通常的powershell ADSI包装器方法,这一切都运行良好。