In this previous post : PowerShell wrapper for creating a new distribution group, I created a script for creating a new distribution group. I wanted to take that a step further and prompt the SysAdmin to add users. I created a new recursive function called AddToDistributionGroup. In this code, I prompt for a group name, and a user to add. The SysAdmin types in the first few parts of the name (I could have used samaccountname) and then I then loop through ADusers with that name asking the SysAdmin if that is the user they want to add.
function JBMURPHY-EXCHANGE-AddToDistributionGroup {
Param( [parameter(Mandatory = $true)]$GroupName,
[parameter(Mandatory = $true)]$UserToAdd)
JBM-EXCHANGE-StartPSSESSION
if (!($GroupName)) {write-host "you need to specify a group name"
break}
if (($UserToAdd)) {
$UserToAdd=$UserToAdd+"*"
Get-aduser -filter {(name -like $UserToAdd) -and (Enabled -eq $true)} | foreach-object {
$UserName=$_.Name
$message = "Add $UserName to the group: $GroupName"
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes","Yes add $UserName to the group $GroupName"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No","No, don't add $UserName to the group $GroupName?"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
if ($result -eq 0){
write-host "Adding $UserName"
Add-DistributionGroupMember -Identity $GroupName -Member $UserName
}
}
JBM-EXCHANGE-AddToDistributionGroup $GroupName
}
}
* Note, there is not any error checking to see if the group exists. I am mainly using this code to be called from a NewDistributionGroup script, where I know the name of the group. I may add a lookup to see if the group exists at some point.
** Now that I think about it, this is for any type group, not just distribution groups.
Comments are closed.