Forum Discussion
PowerShell script to add users to multiple exchange server distribution list.
I'm not familiar with 'Add-DistributionGroupMember', but I certainly can help with your scripting.
Instead of using 'Read-Host' for getting input, let's use parameters, this way we start with a nice list of e-mails and groups.
Following the same line, we can ditch that dictionary, and create an extra parameter. With the 'ValidateSet' attribute we make sure only the options we want are used.
[CmdletBinding()]
param (
[Parameter()]
[string[]]$EmailList,
[Parameter()]
[string[]]$GroupNames,
[Parameter()]
[ValidateSet('Basware')]
[string]$RequestType
)
On the next part I wasn't 100% sure, but I think you wanted to iterate through the e-mails, and remove them from a group and add to another right? If so, we can use a 'foreach' loop.
# For each e-mail in the e-mail list.
foreach ($user in $EmailList) {
# If the input request is equal to 'Bsware'.
if ($RequestType -eq 'Basware') {
# Instead of using 'Select-Object -ExpandProperty Name' we can use this notation.
# This avoids using the pipeline, and reduces complexity.
$user_groups = (Get-ADPrincipalGroupMembership -Identity $user).Name
if ($user_groups -contains 'buyer') {
Remove-DistributionGroupMember -Identity "Basware_AD_GRoup" -Member $user -ErrorAction Stop
Add-DistributionGroupMember -Identity "Basware_AD_GRoup" -Member $user -ErrorAction Stop
Write-Host "User $user added to group successfully."
}
# Is this necessary? It's doing the same as above.
elseif ($user_groups -contains 'requester') {
Remove-DistributionGroupMember -Identity "Basware_AD_GRoup" -Member $user -ErrorAction Stop
Add-DistributionGroupMember -Identity "Basware_AD_GRoup" -Member $user -ErrorAction Stop
Write-Host "User $user added to group successfully."
}
}
}
Following the same vibe, we go through the groups.
foreach ($group in $GroupNames) {
try {
# Do you mean to add them all at once, or one at the time? if one at the time, it's better to use the upper loop.
Add-DistributionGroupMember -Identity $group -Member $UserEmails -ErrorAction Stop
Write-Host "User $UserEmail added to group $GroupName successfully."
}
catch {
Write-Host "Error adding user $UserEmail to group $GroupName $_"
}
}
And this is how you use it. Suppose you save this file as 'C:\SuperScript.ps1'.
You would use it like this:
# A list of e-mails, one at each line.
$mailList = Get-Content -Path C:\emailList.txt
# Same with groups.
$groupList = Get-Content -Path C:\groupList.txt
& C:\SuperScript.ps1 -EmailList $emailList -GroupNames $groupList -RequestType Basware
Hope it helps.
Happy scripting!
The requirement is to iterate using dictionary e.g $requesttype @{Bsware=Approver} , likewise many value can pass to this so it should loop through each request type if the request type only one then run for this nly or if there is multiple request type then it should iterate and use the similar logic for other Ad groups.