Import-Csv with a dialog box - powershell

I am trying to add a dialog box into my Import-Csv script in Powershell v7. Basically, I do not want to remember different names of .csv files that have been exported from another script, so this will make it a lot easier. I have looked around and could not find anything that relates to what I am getting.
The code I have is this:
Write-Host "This will bulk add users to an AD group." -ForegroundColor Yellow
" "
# Import the data from CSV file and assign it to variable
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$OpenFIleDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.InitialDirectory = $InitialDirectory
$OpenFileDialog.Filter = "CSV (*.csv) | *.csv"
$OpenFileDialog.ShowDialog() | Out-Null
$Path = $OpenFileDialog.Filename
$Users = Import-Csv -Path $Path
# Specify target group where the users will be added to
# You can add the distinguishedName of the group. For example: CN=Pilot,OU=Groups,OU=Company,DC=exoip,DC=local
$Group = Read-Host "Enter in the target group name"
# Start transcript
Start-Transcript -Path "C:\Output Log\Users Logs\Add-ADUsers.log" -Append -UseMinimalHeader
foreach ($User in $Users) {
# Retrieve UPN
$UPN = $User.UserPrincipalName
# Retrieve UPN related SamAccountName
$ADUser = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'" | Select-Object SamAccountName
# User from CSV not in AD
if ($null -eq $ADUser) {
Write-Host "$UPN does not exist in AD" -ForegroundColor Red
}
else {
# Retrieve AD user group membership
$ExistingGroups = Get-ADPrincipalGroupMembership $ADUser.SamAccountName | Select-Object Name
# User already member of group
if ($ExistingGroups.Name -eq $Group) {
Write-Host "$UPN already exists in $Group" -ForeGroundColor Yellow
}
else {
# Add user to group
Add-ADGroupMember -Identity $Group -Members $ADUser.SamAccountName
Write-Host "Added $UPN to $Group" -ForeGroundColor Green
}
}
}
Stop-Transcript
" "
Remove-Variable -Name Users
Write-Host "Users have finished adding to $group" -ForegroundColor Yellow
" "
}
The results of the output is this:
The search filter cannot be recognized
+ CategoryInfo : NotSpecified: (:) [Get-ADUser], ADException
+ FullyQualifiedErrorId : ActiveDirectoryServer:8254,Microsoft.ActiveDirectory.Management.Commands.GetADUser
+ PSComputerName : localhost
does not exist in AD
Note: "does not exist in AD" has a blank in front of it. I suspect it is because the import is not reading the file, but I cannot make sense of how to fix it.
Any help will be much appreciated!
Thank you in advanced.

Related

Trying to remove a Computer Object from AD security group using powershell & importing from a CSV file

having a heck of a time with this. Also, wanted to preface this with I'm not the best at PowerShell as I'm just starting out. I have a CSV file that I'm trying to read the first column which happens to be 'AssetName'. These are AD joined computers.
#Get Computer
$Computers = Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv' | Select-Object AssetName
$Group = "Sec Group Name"
# Set the ErrorActionPreference to SilentlyContinue, because the -ErrorAction
# option doesn't work with Get-ADComputer or Get-ADGroup.
$ErrorActionPreference = "SilentlyContinue"
# Get the computer and group from AD to make sure they are valid.
$ComputerObject = Get-ADComputer $Computer
$GroupObject = Get-ADGroup $Group
Foreach ($Computer in $Computers){
if ($GroupObject) {
# If both the computer and the group exist, remove the computer from
# the group.
Remove-ADGroupMember $Group `
-Members (Get-ADComputer $Computer).DistinguishedName -Confirm:$False
Write-Host " "
Write-Host "The computer, ""$Computer"", has been removed from the group, ""$Group""." `
-ForegroundColor Yellow
Write-Host " "
}
else {
Write-Host " "
Write-Host "I could not find the group, ""$Group"", in Active Directory." `
-ForegroundColor Red
Write-Host " "
}
}
else {
Write-Host " "
Write-Host "I could not find the computer, $Computer, in Active Directory." `
-ForegroundColor Red
Write-Host " "
}
Upon doing so, I want to remove that Asset from a specific security group. Whenever I run my script, I get this error. I don't know why it's reading it with the "#{AssetName=CompName}".
The computer, "#{AssetName=CompName}", has been removed from the group, "Sec Group Name".
Any help would be much appreciated.
With your first line you are saving a list of PSObjects to $Computers.
$Computers = Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv' | Select-Object AssetName
These Objects look like this #{AssetName=Computername}
When you iterate these objects you need to specify that you only want the value of the AssetName parameter
Get-ADComputer $Computer.AssetName
Another (in my opinion better) way would be to stop using Select-Object (which storing the returned objects in $computers) and only storing a list of AssetNames in $computers like this:
$Computers = (Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv').AssetName
EDIT:
You can also use -ExpandProperty with your Select-Object:
$Computers = Import-csv -Delimiter ";" -Path 'C:\Path\to\File.csv' | Select-Object -ExpandProperty AssetName

Powershell Catch Error: Unable to find a default server with Active Directory Web Services running

Need help to catch the error. Whenever my network connection is unstable my get-ad script will be terminated.
$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path
$Date = Get-Date -Format yyyy_MM_dd_THHmm
Start-Transcript -Path "$ScriptDir\Logs.log" -Append
$List = Import-Csv "$ScriptDir\Accounts.csv"
$TotalCount = $List.Length
$CurrentCount = 0
Write-Host 'Total Count: '$TotalCount
ForEach ($user in $List) {
# Retrieve UserSamAccountName and ADGroup
$Groups = $User.Group
$UserSam = $User.SamAccountName
# Retrieve SamAccountName and ADGroup
$ADUser = Get-ADUser -Filter "SamAccountName -eq '$UserSam'" | Select-Object SamAccountName
$ADGroups = Get-ADGroup -Filter * | Select-Object Name
# User does not exist in AD
if ($ADUser -eq $null) {
Write-Host "$UserSam does not exist in AD" -ForegroundColor DarkCyan
Continue
}
# User does not have a group specified in CSV file
if ($Groups -eq $null) {
Write-Host "$UserSam has no group specified in CSV file" -ForegroundColor Yellow
Continue
}
# Retrieve AD user group membership
$ExistingGroups = Get-ADPrincipalGroupMembership $UserSam | Select-Object Name
foreach ($Group in $Groups.Split(';')) {
# Group does not exist in AD
if ($ADGroups.Name -notcontains $Group) {
Write-Host "$Group group does not exist in AD" -ForegroundColor Gray
Continue
}
# User already member of group
if ($ExistingGroups.Name -eq $Group) {
Write-Host "$UserSam already exists in group $Group." -ForeGroundColor Yellow
}
else {
# User not a member of group
Write-Host "User $UserSam doesn't exists in $Group AD group" -ForegroundColor Red
}
}
$CurrentCount++
$Percentage = [math]::Round($CurrentCount/$TotalCount*100)
Write-Progress -Activity "Building report in progress" -Status "$Percentage% Complete" -PercentComplete $Percentage
}
Stop-Transcript
Write-Output 'Script complete.'
OUTPUT ERROR
Get-ADUser : Unable to find a default server with Active Directory Web Services running.
At C:\Users\JVERE05\Desktop\Powershell\Powershell\CheckIfExist\08_08.ps1:22 char:11
+ $ADUser = Get-ADUser -Filter "SamAccountName -eq '$UserSam'" | Select ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (:) [Get-ADUser], ADServerDownException
+ FullyQualifiedErrorId : ActiveDirectoryServer:1355,Microsoft.ActiveDirectory.Management.Commands.GetADUser
The fully qualified type name is Microsoft.ActiveDirectory.Management.ADServerDownException:
try {
Get-ADUser ... -ErrorAction Stop
}
catch [Microsoft.ActiveDirectory.Management.ADServerDownException] {
<# AD Server is down #>
}
catch {
<# Something else went wrong #>
}

Add users into AD group with correct CSV output

I am trying to add an AD group into user profiles based on an OU
I had a similar script working, so tried to modify it and failed. I am guessing it's the " -Identity $_" it maybe, but I am not good enough to debug.
#Create a new class to hold the info for our CSV entry
Class CSVEntry{
[String]$UserName
[String]$GroupName
[String]$TimeStamp
}
#Creating a list to hold the CSV entries
$Results = New-Object 'System.Collections.Generic.List[PSObject]'
#Defined the name of the group here
$GroupName = 'GROUPS NAME'
$ou = 'ou=XX,ou=XX,ou=XX,dc=XX,dc=local'
Get-ADUser -Filter * -SearchBase $ou | ForEach-Object{
#Add the user to the group here
Add-ADPrincipalGroupMembership -MemberOf $GroupName Identity $_
#Write-Host $_.Name - $groupName
#Build a custom CSVEntry object and add it to the list
$newRecord = [CSVEntry]::new()
$newRecord.UserName = $_.Name
$newRecord.GroupName = $groupName
$newRecord.TimeStamp = Get-Date
#Add the new record to the list
$Results.Add($newRecord)
}
#Export the list of CSV entries
$Results | Export-Csv C:\PS\AddADGroupToUsers.csv
errors:
Add-ADPrincipalGroupMembership : A positional parameter cannot be found that accepts argument 'CN=NAME,OU=XX,OU=XX,OU=XX,OU=XX,DC=XX,DC=LOCAL'.
At line:18 char:5
+ Add-ADPrincipalGroupMembership -MemberOf $GroupName Identity $_
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Add-ADPrincipalGroupMembership], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.AddADPrincipal
GroupMembership
EDIT:
So, the script doesn't actually do any changes, the group doesn't get added to the users. the output on screen is:
WARNING: User is already a member of group XYZ
WARNING: User is already a member of group XYZ
WARNING: User is already a member of group XYZ
UserName GroupName TimeStamp
-------- --------- ---------
shows ok XYZ 14/10/2019 14:50:23
shows ok XYZ 14/10/2019 14:50:23
shows ok XYZ 14/10/2019 14:50:23
All I have changed is the group name to XYZ and username shows ok in the second half. But, shows blank in the top, and I assure you that a) the user isn't already in the group and b) the script isn't adding them
Current tweaked code, warts and all but sanitised:
$groupName = 'GROUP'
$ou = 'setcorrectly'
$cred = Get-Credential -credential dom\usr
$results = Get-ADUser -Filter * -SearchBase $ou -Credential $cred | ForEach-Object {
#Add the user to the group here
try {
Add-ADGroupMember -Identity $groupName -Members $_.DistinguishedName -Credential $cred -ErrorAction Stop
}
catch {
Write-Warning "User $($_.Name) is already a member of group $groupName"
}
# output a PsCustomObject that gets collected in the $results variable
[PsCustomObject]#{
'UserName' = $_.Name
'GroupName' = $groupName
'TimeStamp' = Get-Date
}
}
# output on console
$results | Format-Table -AutoSize
# Export to CSV file
$results | Export-Csv C:\PS\AddADGroupToUsers.csv -NoTypeInformation
Read-Host -Prompt "Press Enter to exit"
CSV output shows the second half of the screen output only, and doesn't say anything is already a member
Below uses Add-ADGroupMember to add user(s) to 1 group instead of Add-ADPrincipalGroupMembership which is used to add 1 user to multiple groups.
It also uses [PsCustomObject]s to output the results, so you don't need to use the Class CSVEntry.
# Define the name of the group here.
# can be either:
# A distinguished name
# A GUID (objectGUID)
# A security identifier (objectSid)
# A Security Account Manager account name (sAMAccountName)
$groupName = '<NAME OF THE GROUP>'
$ou = 'ou=XX,ou=XX,ou=XX,dc=XX,dc=local'
$results = Get-ADUser -Filter * -SearchBase $ou | ForEach-Object {
#Add the user to the group here
$userName = $_.Name
try {
Add-ADGroupMember -Identity $groupName -Members $_.DistinghuishedName -ErrorAction Stop
# output a PsCustomObject that gets collected in the $results variable
[PsCustomObject]#{
'UserName' = $_.Name
'GroupName' = $groupName
'TimeStamp' = Get-Date
}
}
catch {
Write-Warning "User $userName is already a member of group $groupName"
}
}
# output on console
$results | Format-Table -AutoSize
# Export to CSV file
$results | Export-Csv C:\PS\AddADGroupToUsers.csv -NoTypeInformation
Edit
If you want the $results variable to ALSO contain users that are already a member of the group, you could simply move the creation of the [PsCustomObject] below the catch{..} block:
$results = Get-ADUser -Filter * -SearchBase $ou | ForEach-Object {
#Add the user to the group here
$userName = $_.Name
try {
Add-ADGroupMember -Identity $groupName -Members $_.DistinghuishedName -ErrorAction Stop
$status = "User added successfully"
}
catch {
Write-Warning "User $userName is already a member of group $groupName"
$status = "User is already a member"
}
# output a PsCustomObject that gets collected in the $results variable
[PsCustomObject]#{
'UserName' = $userName
'GroupName' = $groupName
'TimeStamp' = Get-Date
'Status' = $status
}
}
Hope that helps

Creating new AD users and adding them to multiple groups from CSV

I have been given the task of creating a school's worth of users (UK Secondary). The PS to create the users from a CSV, what I need to do is add the newly created users to various groups at the same time.
The code I am using is as follows
$DCName = '<DC FQDN>'
Import-Csv -Path "D:\Import.csv" |
ForEach-Object {
$Displayname = $_.'FirstName' + " " + $_.'LastName'
$UPN = $_.'UPN'
$GroupName = $_.'GroupName'
$Prop = #{
Name = $Displayname
DisplayName = $_.'FirstName' + " " + $_.'LastName'
GivenName = $_.'FirstName'
Surname = $_.'LastName'
UserPrincipalName = $UPN
EmailAddress = $UPN
SamAccountName = $_.'SAM'
AccountPassword = (ConvertTo-SecureString $_.'Password' -AsPlainText -Force)
Enabled = $true
Path = $_.'OU'
ChangePasswordAtLogon = $false
Title = $_.'JobTitle'
StreetAddress = $_.'Street'
City = $_.'Town'
State = $_.'County'
PostalCode = $_.'PostCode'
OfficePhone = $_.'Telephone'
Company = $_.'Company'
Department = $_.'Department'
HomeDrive = $_.'HomeDrive'
HomeDirectory = $_.'Home-Directory'
OtherAttributes = #{
'extensionAttribute1'= $_.'ExtendedAttribute1';
'extensionAttribute2'= $_.'ExtendedAttribute2';
'extensionAttribute14'= $_.'ExtendedAttribute14';
'extensionAttribute15'= $_.'ExtendedAttribute15';
'proxyAddresses' = "SMTP:" + $UPN;}
Server = $DCName
}
New-ADUser #prop
Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'
}
The user gets created with all properties correctly set. It fails with the following error
Add-ADGroupMember : Cannot find an object with identity: 'Test.User' under: 'DC=AD,DC=example,DC=uk'.
At C:\Scripts\NewUserFromCSV2.ps1:47 char:10
+ Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Test.USer:ADPrincipal) [Add-ADGroupMember], ADIdentityNotFoundException
+ FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.AddADGroupMember
It looks like the Add-ADGroupMember command can't find the user that has just been created, however, if that is the case I don't understand why.
Also at the moment, my CSV has only one group in the 'GroupName', what would be the best way to add the user to multiple groups? e.g. School-All-Staff, Teaching-Staff, Science-Teachers etc.
Thanks in advance for any help received.
As it's a bulk operation, I would just split the user creation from the group membership.
Create all the users first, then add them to the groups:
$DCName = '<DC FQDN>'
$Users = Import-Csv -Path "D:\Import.csv"
$Users | ForEach-Object {
$Displayname = $_.'FirstName' + " " + $_.'LastName'
$UPN = $_.'UPN'
$Prop = #{
## properties as per original code ##
}
New-ADUser #prop
}
$Users | ForEach-Object {
$GroupName = $_.'GroupName'
Add-ADGroupMember -Identity $GroupName -Members $_.'SAM'
}
The to add the users to multiple groups:
If you've got a semicolon separated list of the groups in GroupName eg
School-All-Staff;Teaching-Staff;Science-Teachers
Split will convert this to an array then you can loop through them:
$_.'GroupName' -split ';' | ForEach-Object {
Add-ADGroupMember $_ –Member $user.'SAM'
}
(edit: updated to semicolon as you have a csv source)
I got it working as a combined script in the end and added in error checking for pre-existing users, existing staff often move to the new school that is being added to the Trust prior to its addition to our AD and get included in the list of users to create.
Also added log file creation to record newly created users and list those whose SAMAccount name already exists so we can check to see if the user does need creating or if they need moving from another School OU.
This is my final code:
#Get deafult variables to tidy up created variables at the end
$ExistingVariables = Get-Variable | Select-Object -ExpandProperty Name
#New User Code Starts Here>
#Variables not set by CSV
#Set DC name to update - prevents errors due to replication delay
$DCName = '<DC FQDN>'
#Create log files
"Users Exist in AD" | Out-File -FilePath "D:\Logs\ExistingUsers-$(get-date -f yyyyMMdd).txt" -Append
"New Users Created" | Out-File -FilePath "D:\Logs\NewUsers-$(get-date -f yyyyMMdd).txt" -Append
#Specify path and file to import
Import-Csv -Path "D:\Import.csv" |
#Iterate through each row in the CSV
ForEach-Object {
#Set per object variables from fields in the CSV
$DisplayName = $_.'FirstName' + " " + $_.'LastName'
$UPN = $_.'UPN'
$GroupName1 = $_.'GroupName1'
$GroupName2 = $_.'GroupName2'
$GroupName3 = $_.'GroupName3'
$GroupName4 = $_.'GroupName4'
$SAM = $_.'SAM'
$Password = $_.'Password'
$SAMTest = Get-ADUser -Filter {(sAMAccountName -eq $SAM)} -Server $DCName
#Splatting Hash Table holds all user attribute properties set in the CSV
$Prop = #{
Name = $DisplayName
DisplayName = $DisplayName
GivenName = $_.'FirstName'
Surname = $_.'LastName'
UserPrincipalName = $UPN
EmailAddress = $UPN
SamAccountName = $_.'SAM'
AccountPassword = (ConvertTo-SecureString $_.'Password' -AsPlainText -Force)
Enabled = $true
Path = $_.'OU'
ChangePasswordAtLogon = $false
Title = $_.'JobTitle'
StreetAddress = $_.'Street'
City = $_.'Town'
State = $_.'County'
PostalCode = $_.'PostCode'
OfficePhone = $_.'Telephone'
Company = $_.'Company'
Department = $_.'Department'
OtherAttributes = #{
'extensionAttribute1'= $_.'ExtendedAttribute1';
'extensionAttribute2'= $_.'ExtendedAttribute2';
'extensionAttribute14'= $_.'ExtendedAttribute14';
'extensionAttribute15'= $_.'ExtendedAttribute15';
'proxyAddresses' = "SMTP:" + $UPN;}
Server = $DCName
}
#Check if SAMAccount name exists in AD and skip existing users
if ($SAMTest -ne $Null)
{
#Get UPN property of the pre-existing user
$Exist = Get-ADUser -Filter {(sAMAccountName -eq $SAM)} -Properties 'userprincipalname'
#write UPN value to variable
$ExistUPN = $Exist.userprincipalname
#Update log of pre-existing users
"$DisplayName exists with email $ExistUPN" | Out-File -FilePath "D:\Logs\ExistingUsers-$(get-date -f yyyyMMdd).txt" -Append
#Write to screen
Write-Host "$DisplayName already exists in AD" -ForegroundColor Red
}
else
{
#Create new user with the attribute properties collected above
New-ADUser #prop
#Check if group fields in CSV were populated, if true add user to group, if false skip
if ($_.'GroupName1'){Add-ADGroupMember -Identity $_.'GroupName1' -Members $_.'SAM' -Server $DCName}
if ($_.'GroupName2'){Add-ADGroupMember -Identity $_.'GroupName2' -Members $_.'SAM' -Server $DCName}
if ($_.'GroupName3'){Add-ADGroupMember -Identity $_.'GroupName3' -Members $_.'SAM' -Server $DCName}
if ($_.'GroupName4'){Add-ADGroupMember -Identity $_.'GroupName4' -Members $_.'SAM' -Server $DCName}
#Update New user log
"$UPN" | Out-File -FilePath "D:\Logs\NewUsers-$(get-date -f yyyyMMdd).txt" -Append
#Write to screen
Write-Host "User $SAM created at $((Get-Date).ToString('hh:mm'))" -ForegroundColor Green
}
}
#End Of New User Code
#Remove variables set by script - keeps PS memory space tidy
$NewVariables = Get-Variable | Select-Object -ExpandProperty Name | Where-Object {$ExistingVariables -notcontains $_ -and $_ -ne "ExistingVariables"}
if ($NewVariables)
{
Write-Host "Removing the following variables:`n`n$NewVariables"
Remove-Variable $NewVariables
}
else
{
Write-Host "No new variables to remove!"
}
I used the bit about clearing up variables because the values seemed to persist if the PowerShell session remained open and it was causing odd things to happen. I also removed the home drive attributes because the file server specified hasn't been implemented yet but management still wants the users in AD now.
For reference my import.csv looks like this
FirstName,LastName,UPN,SAM,Password,OU,JobTitle,Street,Town,County,PostCode,Telephone,Company,Department,ExtendedAttribute1,ExtendedAttribute2,ExtendedAttribute14,ExtendedAttribute15,GroupName1,GroupName2,GroupName3,GroupName4
Test,User,Test.Users#domain.uk,Test.User,,"OU=Admin Staff,OU=User Resources,OU=School,OU=Trust Schools,DC=AD,DC=Trust,DC=org",,Street Name,TownName,County,AA11 1AA,116123,Name Of School,Name Of Trust,,Staff,,,AllStaffGroup,AdminStaffGroup,SpecialPermissionsGroup,Group4

Powershell with Active Directory creating groups

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
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"
}
}
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