Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<#
Author: I. Strachan
Version:
Version History:
Purpose: Add group member from excel worksheet. Scripts is based on Mike Robin's work
http://tinyurl.com/jfmw4o7
#>
[CmdletBinding()]
param(
$xlsxFile = 'Demo-Kruisjes.xlsx',
$WorkSheet = 'Demo'
)
#region
$exportDate = Get-Date -Format ddMMyyyy
#endregion
#Import Worksheet Using D. Finke's ImportExcel module http://tinyurl.com/lbhkhbd
$xlsxADGroupMembers = Import-Excel .\source\xlsx\$xlsxFile -WorkSheetname $WorkSheet
#Select Group names from Object
$Header = $xlsxADGroupMembers |
Get-Member -MemberType NoteProperty |
Where-Object{$_.Name -ne 'UserID'} |
Select-Object -ExpandProperty Name
#Create empty hashtables
$addADGroupMembers = @{}
$delADGroupMembers = @{}
#Get Group membership
$Header |
ForEach-Object{
$Group = $_
$addADGroupMembers.$Group = $xlsxADGroupMembers.Where{$_.$Group -eq '1'} | Select-Object -ExpandProperty 'UserID'
$delADGroupMembers.$Group = $xlsxADGroupMembers.Where{$_.$Group -ne '1'} | Select-Object -ExpandProperty 'UserID'
}
#region Main. Add and remove users to/from groups
$Header |
ForEach-Object{
if($addADGroupMembers.$_){
try{
Add-ADGroupMember -Identity $_ -Members $addADGroupMembers.$_
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{
Write-Warning "AD Object $($Error[0].CategoryInfo.TargetName) not found"
}
}
if($delADGroupMembers.$_){
try{
Remove-ADGroupMember -Identity $_ -Members $delADGroupMembers.$_ -Confirm:$false
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]{
Write-Warning "AD Object $($Error[0].CategoryInfo.TargetName) not found"
}
}
}
#endregion
#region Export for futher processing
$GroupMembers =@{
Groups = $Header | Get-ADGroup -Properties WhenCreated
Added = $addADGroupMembers
Revoked = $delADGroupMembers
}
$GroupMembers |
Export-Clixml .\export\dsa\ADGroupMembers-$exportDate.xml -Encoding UTF8
#endregion
Owner

irwins commented Nov 29, 2016

29-11-2016 Added and extra step. Exported $GroupMembers to xmlfile

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment