如何使用PowerShell使另一个AD组的AD组成员?

时间:2013-09-18 07:33:00

标签: powershell active-directory windows-server-2008-r2

我正在尝试制作批量脚本来创建组并使某些组成为其他组(子组)的成员。我想创建组TestGroup1,TestGroup2(memberOf TestGroup1),TestGroup3(memberOf TestGroup1)

所以这是我的csv文件,其中包含输入组:

bulk_import.csv:

GroupName,GroupType,GroupLocation,Member

TestGroup1,Global,"OU=arSearch",
TestGroup2,Global,"OU=arSearch",TestGroup1
TestGroup3,Global,"OU=arSearch",TestGroup1

以及创建组的脚本如下:

bulk_ad_group_creation.ps1

Import-Module ActiveDirectory
#Import CSV
$csv = @()
$csv = Import-Csv -Path "C:\bulk_import.csv"

#Get Domain Base
$searchbase = Get-ADDomain | ForEach {  $_.DistinguishedName }

#Loop through all items in the CSV
ForEach ($item In $csv)
{
  #Check if the OU exists
  $check = [ADSI]::Exists("LDAP://$($item.GroupLocation),$($searchbase)")

  If ($check -eq $True)
  {
    Try
    {
      #Check if the Group already exists
      $exists = Get-ADGroup $item.GroupName
      Write-Host "Group $($item.GroupName) alread exists! Group creation skipped!"
    }
    Catch
    {
      #Create the group if it doesn't exist
      $create = New-ADGroup -Name $item.GroupName -GroupScope $item.GroupType -Path ($($item.GroupLocation)+","+$($searchbase)) -Member $item.Member
      Write-Host "Group $($item.GroupName) created!"
    }
  }
  Else
  {
    Write-Host "Target OU can't be found! Group creation skipped!"
  }
}

但它始终打印出无法找到参数-Member的信息,请告知。

我正在使用Windows Server 2008 R2。

1 个答案:

答案 0 :(得分:0)

我能够通过更改脚本来解决它:

Import-Module ActiveDirectory
#Import CSV
$csv = @()
$csv = Import-Csv -Path "C:\bulk_import.csv"

#Get Domain Base
$searchbase = Get-ADDomain | ForEach {  $_.DistinguishedName }



#Loop through all items in the CSV
ForEach ($item In $csv)
{
  #Check if the OU exists
  $check = [ADSI]::Exists("LDAP://$($item.GroupLocation),$($searchbase)")

  If ($check -eq $True)
  {
    Try
    {
      #Check if the Group already exists
      $exists = Get-ADGroup $item.GroupName
      Write-Host "Group $($item.GroupName) alread exists! Group creation skipped!"
    }
    Catch
    {
      #Create the group if it doesn't exist
      $create = New-ADGroup -Name $item.GroupName -GroupScope $item.GroupType -Path ($($item.GroupLocation)+","+$($searchbase))
      Write-Host "Group $($item.GroupName) created!"
      if($item.MemberOf -eq ""){
         Write-Host "Group don't have parent"
         }else{
             Add-ADGroupMember -Identity $item.MemberOf -Member $item.GroupName 
           }
    }
  }
  Else
  {
    Write-Host "Target OU can't be found! Group creation skipped!"
  }
}