PowerShell script : Test member of

Active Directory logo

#####################################################

#  This script does a bulk AD group membership

#           add based on an input csv. Delimiter by « ; ».

#           (No check ,error generate if already exist)

#           CSV input is the matrix file with « profil »

#           column = global and « droit » column = local

###########################################################

 

#################################

# Function preparation

##############################

function Check-IsGroupMember{

Param($user,$grp)

$strFilter = « (&(objectClass=Group)(name= » + $grp + »)) »

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher

$objSearcher.SearchRoot = $objDomain

$objSearcher.PageSize = 1000

$objSearcher.Filter = $strFilter

$objSearcher.SearchScope = « Subtree »

$colResults = $objSearcher.FindOne()

$objItem = $colResults.Properties

([string]$objItem.member).contains($user)

}

 

#################################

# Add member to AD Group

#################################

 

######### Import CSV AD group Member #########

[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

$Csv = @()

$Inputfile = $OpenFileDialog.filename

$Csv = Import-Csv $InputFile -Delimiter « ; »

 

####### Loop through all items in the CSV ######

ForEach ($item In $csv){

#Check if the OU exists

$Member = $Item.member

$GroupMember = $Item.GroupMember

#Create the group if it doesn’t exist

Try{

# Check if the Group already exist

$MemberExist = Get-ADGroup $Member

$GroupeMemberExist = Get-ADGroup $GroupMember

}

Catch{

Write-Host « Group : ‘$Member or $GroupMember’ doesn’t exist. »

}

Finally{

$test = Check-IsGroupMember $Member $GroupMember

IF($test -eq « True »){

Write-host $Member « is already member of » $Member

}

Else{

Add-ADGroupMember -Identity $GroupMember -Members $Member | Out-File « c:\temp\ADGrouplog.txt » -append

Write-host $Member « add to » $GroupMember

}#Finally 2

}#Finally 1

}# Foreach

Laisser un commentaire