Skip to content

Instantly share code, notes, and snippets.

@gravcat
Created January 4, 2019 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gravcat/b19fd50c05c71df3ba1fb6a0e68bc3c7 to your computer and use it in GitHub Desktop.
Save gravcat/b19fd50c05c71df3ba1fb6a0e68bc3c7 to your computer and use it in GitHub Desktop.
<#
.NAME
add_user_to_ad_groups.ps1
.PARAMETER username
Username which you will add group memberships to.
.PARAMETER import_file
If not running in single_group mode (see single_group parameter), declare the CSV file that holds all desired groups to make the user become a member of.
.PARAMETER single_group
If you do not have an import_file, do not want to use the default, and only have a single_group to declare, specify here as a string.
This supports an array, but if you are adding multiple you should really move it to an import_file, and store that in source.
.EXAMPLE
./add_user_to_ad_group.ps1 -username nicholas.thieling
.EXAMPLE
./add_user_to_ad_group.ps1 -username nicholas.thieling -single_group "APP_OrderDataSearch_Admin-QA"
.EXAMPLE
./add_user_to_ad_group.ps1 -username nicholas.thieling -import_file "C:\Users\nicholas.thieling\Downloads\some_department_adgroups.csv"
#>
param(
[Parameter(Mandatory=$true)]
[String]
$username,
[String]
$import_file = "devops_engineer_ad_groups.csv",
[String]
$single_group
)
$ErrorActionPreference = "Stop"
Import-Module ActiveDirectory
if ($null -eq (Get-ADUser -Filter {sAMAccountName -eq $username})) {
Write-Error "Unable to find account ""$username"", please verify. You also may need to run powershell as another user to do this operation."
}
if ($single_group) {
foreach ($group in $single_group) {
Add-ADGroupMember -Identity $group -Member $username
}
}
else {
$groups = Import-CSV $import_file
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Member $username
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment