我正致力于一项计划,该计划将为离开我们网络的用户实现自动化分离流程。它执行的任务之一是将用户帐户从其所在的OU移动到Former Employees
OU。即使我在使用DirectoryServices
执行其他流程时没有遇到任何问题,我也一直遇到此问题。到目前为止,这是我的代码(注意:我知道我需要停止捕捉和吃掉所有异常。这将在发布之前得到解决和纠正。有关哪些例外我应该抓住以及哪些我不应该被赞赏的建议):
private const string AD_DOMAIN_NAME = "domain.com";
private const string AD_NEW_PASSWORD = "TestPassword123";
private const string AD_FORMER_EMPLOYEES_OU = "LDAP://OU=Former Employees,DC=domain,DC=com";
static DirectoryEntry CreateDirectoryEntry(string connectionPath,
string adUserName, string adPassword)
{
DirectoryEntry ldapConnection = null;
try
{
ldapConnection = new DirectoryEntry(AD_DOMAIN_NAME, adUserName, adPassword);
ldapConnection.Path = connectionPath;
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
}
catch (Exception ex)
{
MessageBox.Show("Exception Caught in createDirectoryEntry():\n\n" + ex.ToString());
}
return ldapConnection;
}
private void btnProcessSeparation_Click(object sender, EventArgs e)
{
if (cboOffice.SelectedItem != null && lstUsers.SelectedItem != null)
{
string userOU = cboOffice.SelectedItem.ToString();
string userName = lstUsers.SelectedItem.ToString();
string userDn = "LDAP://OU=" + userOU + ",OU=Employees,DC=domain,DC=com";
using (DirectoryEntry ldapConnection = CreateDirectoryEntry(userDn))
{
using (DirectorySearcher searcher = CreateDirectorySearcher(ldapConnection,
SearchScope.OneLevel, "(samaccountname=" + userName + ")", "samaccountname"))
{
SearchResult result = searcher.FindOne();
if (result != null)
{
using (DirectoryEntry userEntry = result.GetDirectoryEntry())
{
if (userEntry != null)
{
using (DirectoryEntry formerEmployees = CreateDirectoryEntry(
AD_FORMER_EMPLOYEES_OU))
{
userEntry.MoveTo(formerEmployees); // This line throws an DirectoryServicesCOMException.
}
userEntry.CommitChanges();
userEntry.Close();
MessageBox.Show("Separation for {0} has completed successfully.", userName);
}
}
}
}
}
}
else
{
MessageBox.Show("Error, you did not select an OU or a user. Please try again.");
}
}
以上代码在userEntry.MoveTo(formerEmployees);
行之前一直运行正常。该行会引发DirectoryServicesCOMException
附加信息An invalid dn syntax has been specified.
这很奇怪,因为我使用的格式与其他工作正常的DirectoryEntry
相同。我添加了一个断点并确认formerEmployees
设置为:LDAP://OU=Former Employees,DC=domain,DC=com
。我直接从Active Directory中的OU LDAP://
属性复制distinguishedName
之后的所有内容,以确保其正确无误。
OU名称中的空格是否导致问题?我让它工作一次就好了,继续执行其他任务,并且必须改变了一些破坏了这个的东西。我一直在考虑代码太多了,我似乎无法理解为什么它认为我发送了一个无效的dn。
感谢您的帮助!
答案 0 :(得分:1)
@David指出我正确的方向确保我对OU有正确的权限后,我发现了问题。我添加了一个重载的CreateDirectoryEntry方法,该方法使用用户名和密码(这是我在上面的代码中添加的内容)。但是,如果您在上面的代码中注意到,我调用仅采用连接路径的方法。
感谢@David的帮助!
答案 1 :(得分:1)
希望这会有所帮助:
DirectoryEntry eLocation = Conexion.Conectar(Localitation);
DirectoryEntry nLocation =Conexion.Conectar(NewLocalitation);
string newName = eLocation.Name;
eLocation.MoveTo(nLocation, newName);
nLocation.Close();
eLocation.Close();