ike*_*kel 3 c# active-directory
是否有使用 C# 从 AD 中删除计算机帐户的示例?
我搜索了很多来源,但都是关于用户帐户的。
在这里添加了我的代码,由于某种原因,我总是出错。
public static bool checkExistingPC(string compName,string userName,string userPwd )
{
try
{
DirectoryEntry entry = new DirectoryEntry("LDAP://test.com",userName,userPwd,AuthenticationTypes.Secure);
DirectorySearcher mySearcher = new DirectorySearcher(entry);
mySearcher.Filter = "(&(objectClass=computer)(|(cn=" + compName + ")(dn=" + compName + ")))";
foreach (SearchResult result in mySearcher.FindAll())
{
if (result != null)
{
MessageBox.Show("computer GetDirectoryEntry():" + result.Path+"\n"+"computer path: "+result.Path);
DirectoryEntry entryToRemove = new DirectoryEntry(result.Path,userName,userPwd);
entry.Children.Remove(entryToRemove);
return true;
}
else
{
return false;
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果您使用 .NET 3.5 及更高版本(如果您不是 - 是时候升级了!),您应该查看System.DirectoryServices.AccountManagement(S.DS.AM) 命名空间。在这里阅读所有相关信息:
基本上,您可以定义域上下文并轻松找到 AD 中的用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the computer in question
ComputerPrincipal computer = ComputerPrincipal.FindByIdentity(ctx, "NAME");
// if found - delete it
if (computer != null)
{
computer.Delete();
}
Run Code Online (Sandbox Code Playgroud)
新的 S.DS.AM 使在 AD 中与用户、计算机和组一起玩变得非常容易!
| 归档时间: |
|
| 查看次数: |
8420 次 |
| 最近记录: |