使用powershell将domain1中的用户添加到domain2组?

时间:2018-04-02 19:43:14

标签: powershell

我正在寻找一些可以将用户从一个域添加到另一个域组的powershell代码。我似乎无法找到使用System.DirectoryServices的神奇代码。

############### 
# Query user 
################ 
# Variables 
$path="GC://ldap-server.company.com" 
# To limit the information returned add properties. Use an empty string to 
pull everything 
$property="objectcategory,distinguishedname,cn,mailnickname,samaccountname" 
$searchFilter="(&(objectClass=User)(samaccountname=joker))" 

$rootEntry = New-Object System.DirectoryServices.DirectoryEntry $path 
$search= New-Object System.DirectoryServices.DirectorySearcher $rootEntry; 
if ($properties) { 
    foreach ($property in [regex]::split($properties, ", ?")) { 
        [void]$search.PropertiesToLoad.Add($property); 
    } 
} 
$search.Filter = $searchFilter; 
$searchResults = $search.FindOne();
$user = $searchResults.GetDirectoryEntry() 
$user_dn = $searchResults.GetDirectoryEntry().distinguishedName; 
# to find the first or only result, use $searchResults = $search.FindOne(); 

################ 
#Query group 
################ 
# Same as Query user, just change 
$property=""; 
$searchFilter="(&(objectClass=Group)(samaccountname=mygroup))";
$search.Filter = $searchFilter; 
$searchResults = $search.FindOne();

################ 
#Add user to group 
################ 
# From your group query 
$group_dn = $searchResults.GetDirectoryEntry().distinguishedName

我尝试了这个,但它似乎没有添加用户并且是ADSI:

$Group = [ADSI]"LDAP://"+$group_dn
$User = [ADSI]"LDAP://"+$user_dn

If ($Group.IsMember($User.ADsPath) -eq $False)
{
    $Group.Add($User.ADsPath)
}

1 个答案:

答案 0 :(得分:0)

我很遗憾不得不do this the hard way一次(域名迁移,其中源域仍在Windows Server 2008上)。您需要做的是从远程域添加用户或组作为外部安全主体:

...
$group_dn = $searchResults.GetDirectoryEntry().distinguishedName

$fsp = New-Object Security.Principal.NTAccount('DOM1', 'username')
$sid = $fsp.Translate([Security.Principal.SecurityIdentifier]).Value

$group = New-Object DirectoryServices.DirectoryEntry("LDAP://$group_dn")

[void]$group.Member.Add("<SID=$sid>")
$group.CommitChanges()
$group.Close()

如果可能,您应该使用ActiveDirectory模块(至少需要Windows Server 2008 R2并访问AD Web服务)。