使用C#更改AD用户终端服务器属性

时间:2015-04-21 13:37:35

标签: c# properties directoryentry

我使用System.DirectoryServices.DirectoryEntry创建AD用户,除了一些远程桌面细节属性外,一切正常。

例如:

newUser.Properties["msTSConnectClientDrives"].Value = false;
newUser.Properties["msTSConnectPrinterDrives"].Value = false;
newUser.Properties["msTSDefaultToMainPrinter"].Value = false;

这不会抛出任何异常,所以我猜在对象中找到了属性,但它们没有任何效果。当我进入该用户的属性窗口时,在“环境”选项卡下,仍然会检查这3个复选框。

我是否遗漏了这些属性特有的东西?

感谢您的帮助。

编辑:

抱歉,我一直很忙,这是代码示例:

    private string CreateNewADAccount(string accountName, string accountPassword)
    {
        try
        {
            PrincipalContext context = new PrincipalContext(ContextType.Domain, "SV-LITE", @"LITE\xxxxxxxx", "yyyyyyyy");

            UserPrincipal newUser = new UserPrincipal(context);
            newUser.SamAccountName = accountName;
            newUser.UserPrincipalName = accountName;
            newUser.Name = "LiteUser2015 - " + accountName;
            newUser.DisplayName = "LiteUser2015 - " + accountName;
            newUser.SetPassword(accountPassword);
            newUser.PasswordNeverExpires = true;
            newUser.UserCannotChangePassword = true;

            newUser.Save();

            // Set advanced properties
            if (newUser.GetUnderlyingObjectType() == typeof(DirectoryEntry))
            {
                DirectoryEntry entry = (DirectoryEntry)newUser.GetUnderlyingObject();

                entry.Properties["msTSConnectClientDrives"].Value = false;
                entry.Properties["msTSConnectPrinterDrives"].Value = false;
                entry.Properties["msTSDefaultToMainPrinter"].Value = false;
                entry.Properties["msTSInitialProgram"].Value = "test";

                entry.CommitChanges();
            }

            return newUser.Guid.ToString();

        }
        catch (Exception e)
        {
            MessageBox.Show("Failed to create PrincipalContext. Exception: " + e);
        }

        return null;
    }

1 个答案:

答案 0 :(得分:1)

进行更改后,您必须调用CommitChanges - newUser.CommitChanges();

请参阅https://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.commitchanges%28v=vs.110%29.aspx

  

默认情况下,对属性的更改在本地进行到缓存..