Again, you’ll need the Windows 2008 r2 ActiveDirectory module for this to work:
import-module ActiveDirectory
Some static variables:
$default_securitygroup_ou="OU=MySecurityGroups,"
And the functions:
function add_security_group([string]$StrGroupName)
{
$check = get-adgroup -Filter { name -eq $StrGroupName }
if($check -eq $null)
{
$ad_path = $default_securitygroup_ou + (get-addomain).distinguishedname
New-ADGroup -Path $ad_path -name $StrGroupName -GroupScope Global -GroupCategory Security
write-host "- Security Group created - OK" -ForeGroundColor Green
}
else
{
write-host "- Security Group allready exists" -ForeGroundColor Yellow
}
}
function add_user_to_group([string]$username, [string]$security_group)
{
$grp = get-adgroup -Filter { name -eq $security_group }
if ($grp -eq $null)
{
write-host "- Security Group does not exist - ERROR" -ForeGroundColor Red
}
else
{
# group does exist, lets see if the users is allready a member
$members = get-adgroupmember -Identity $security_group
foreach ($mem in $members)
{
if($mem.samAccountName -eq $username)
{
$found = $true
}
}
if ($found)
{
write-host "- User is allready a member of this Security Group - WARNING" -ForegroundColor Yellow
}
else
{
add-adgroupmember -identity $security_group $username
write-host "- User succesfully added to Security Group - OK" -ForegroundColor Green
}
}
}