正如使用powershell中的cmdlet所述,这不是一个选项。我试过像这样使用.NET。
$Source = @"
using System;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
namespace some.NameSpace
{
public static class ADClass
{
public static void AddUserToGroup(string userId, string groupName, string domainId)
{
try
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domainId))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, groupName);
group.Members.Add(pc, IdentityType.UserPrincipalName, userId);
group.Save();
}
}
catch (Exception e)
{
throw e;
}
}
}
}
"@
$Assem =
("System.DirectoryServices.dll",
"System.DirectoryServices.AccountManagement.dll)
Add-Type -TypeDefinition $Source -Language CSharp -ReferencedAssemblies $Assem
[some.NameSpace.ADClass]::AddUserToGroup(myUserName, myGroupName, myDomainName)
然而,它很难调试,我不确定它是否工作,我的代码是错误的,或者我只是无法联系AD。