Hey Folks,
I am building a PowerShell script to create AD Groups (Global and DomainLocal) by Importing their names from a Csv file.
I am having a hard time handling exceptions that will be generated in case Groups already exist.
What I want to achieve is if the Groups do not exist by the name in Csv then PS should create them and show message “Groups have been created” and if they already exist then it should display “Groups already exist” line by line so that if one exists and the other one doesn’t then it should display the corresponding message.
What is happening is that PS doesn’t display a message when it has created groups and when exception does occur it displays message only for Global Group not Local.
Please advise
Here’s the code -
Try
{
New-ADGroup -Name TestGlobal -GroupCategory Security -GroupScope Global -ManagedBy TEMP01 -Description “Owner is TEMP01” -Path (Some OU)
}
Catch [Microsoft.ActiveDirectory.Management.ADException]
{
if ($_ -like “The specified group already exists”)
{
Write-Host “!!! GLOBAL GROUP ALREADY EXISTS !!!”
}
elseif ($_ -eq $null)
{
Write-Host " GLOBAL GROUP CREATED SUCCESSFULLY "
}
}
Try
{
New-ADGroup -Name TestLocal -GroupCategory Security -GroupScope DomainLocal -ManagedBy TEMP02 -Description “Owner is TEMP02” -Path (Some OU)
}
Catch [Microsoft.ActiveDirectory.Management.ADException]
{
if ($_ -like “The specified group already exists”)
{
Write-Host “!!! LOCAL GROUP ALREADY EXISTS !!!”
}
elseif ($_ -eq $null)
{
Write-Host " LOCAL GROUP CREATED SUCCESSFULLY "
}
}