Reputation: 69
I have been tasked with creating a bunch of security groups for Active Directory on a 2016 Windows Server. At the moment I have this code
$CSVLocation = Read-Host -Prompt "Please enter the path of CSV file"
$Groups = Import-CSV $CSVLocation
foreach ($Group in $Groups) {
$Groupname = Get-ADGroup -Identity $Group.Group
if ($Groupname -eq $null) {
New-ADGroup -Name $Group.Group -Path $group.GroupLocation -GroupScope $Group.GroupType
}
else {
echo "Group existes"
}
}
This is code is trying to create a group if that group doesn't exist and if it does then skip the entry in the CSV. As of this moment, all it does it pump out Get-ADGroup errors about how it can't find the group and then skips the creation of it.
The CSV format is like such:
Group,GroupType,GroupLocation
Group01,Universal,"OU=Test,DC=Example,DC=Local"
Group02,Universal,"OU=Test,DC=Example,DC=Local"
Group03,Universal,"OU=Test,DC=Example,DC=Local"
Error Message:
Get-ADGroup : Cannot find an object with identity: 'AU-CTX-RDP' under: 'DC=Example,DC=local'.
At C:\Users\Administrator\Desktop\Scripts\Import Groups.ps1:10 char:14
+ $Groupname = Get-ADGroup -Identity $Group.Group
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (AU-CTX-RDP:ADGroup) [Get-ADGroup], ADIdentityNotFoundException
+ FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.GetADGroup
Upvotes: 0
Views: 8159
Reputation: 1
Run this script to create bulk users in Powershell, Task will be completed within 30 seconds
New-ADGroup "-Name -GroupScope -GroupSecurity -GroupName" -Path “OU=OUWhereIStoreMyGroups" -Description
Upvotes: 0
Reputation: 5232
If you query for a not existing group you get a terminatig error. So the script execution would stop. To avoid this you can use -ErrorAction SilentlyContinue
. This way it should work actually
$CSVLocation = Read-Host -Prompt "Please enter the path of CSV file"
$Groups = Import-CSV $CSVLocation
foreach ($Group in $Groups) {
if (-not (Get-ADGroup -Filter "Name -eq '$($group.Group)'" -ErrorAction SilentlyContinue)) {
New-ADGroup -Name $Group.Group -Path $group.GroupLocation -GroupScope $Group.GroupType
}
else {
"Group '$($Group.Group)' already exists"
}
}
Upvotes: 2