Create groups in Active Directory
<#
.SYNOPSIS
Create AD Group
.DESCRIPTION
Create an AD Group with a member group when specified.
.INPUTS
CSV-file with AD groups, group type, ou and member which should be created.
GroupName,GroupType,GroupLocation
GG_DATA_AS0P1011_DIS_OHW_LBZ_RW,Global,"OU=Data,OU=GG,OU=Groepen,OU=Organisatie",
LG_DATA_AS0P1011_DIS_OHW_LBZ_RW,DomainLocal,"OU=Data,OU=LG,OU=Groepen,OU=Organisatie",GG_DATA_AS0P1011_DIS_OHW_LBZ_RW
.OUTPUTS
.NOTES
Version: 1.1
Author: Ivo Dijkgraaf
Creation Date: 16-11-2016
.EXAMPLE
#>
#---------------------------------------------------------[Initialisations]--------------------------------------------------------
Import-Module ActiveDirectory
#Dot Source required Function Libraries
. "P:\PowerShell\Functions\Default_Functions.ps1"
#----------------------------------------------------------[Declarations]----------------------------------------------------------
# Path where the script is run from
$scriptPath = Get-ScriptPath
$importFile = "$scriptPath\ADGroups.csv"
$groupsCsv = Import-Csv -Path $importFile
#-----------------------------------------------------------[Execution]------------------------------------------------------------
#Get Domain Base
$searchbase = Get-ADDomain | ForEach { $_.DistinguishedName }
#Loop through all items in the CSV
ForEach ($group In $groupsCsv)
{
#Check if the OU exists
$check = [ADSI]::Exists("LDAP://$($group.GroupLocation),$($searchbase)")
If ($check -eq $True)
{
# Create the Group
Try
{
#Check if the Group already exists
$exists = Get-ADGroup $group.GroupName
Write-Host "Group $($group.GroupName) alread exists! Group creation skipped!"
}
Catch
{
#Create the group if it doesn't exist
$create = New-ADGroup -Name $group.GroupName -GroupScope $group.GroupType -Path ($($group.GroupLocation)+","+$($searchbase))
Write-Host "Group $($group.GroupName) created in $($group.GroupLocation),$($searchbase)!"
}
# Add the member group to the group
If ($group.GroupMember -ne '')
{
Try
{
#Check if the Member Group exists
$memberGroup = Get-ADGroup $group.GroupMember
$targetGroup = Get-ADGroup $group.GroupName
Add-ADGroupMember -Identity $targetGroup -Members $memberGroup
Write-Host "Member Group $($group.GroupMember) added to $($group.GroupName)!"
}
Catch
{
Write-Host "The Member Group $($group.MemberGroup) does not exist!"
}
}
}
Else
{
Write-Host "Target OU can't be found! Group creation skipped!"
}
}