Issue with Switch

Please can someone help. I have written the script below:

write-host "1. Add a user to the AD group"

write-host "2. Quit"

write-host ""

$choice=read-host "Enter a number to continue"

switch ($choice)


 1 {




foreach ($user in $username)


$GroupMemberUsernames = (Get-ADGroupMember -Identity "ADGroupX" -recursive | get-aduser -properties SamAccountName).SamAccountName

    If ((Get-ADUser -Filter { SamAccountName -eq $User }).Count -eq 0) {

      Write-Host "$User does not exist in Active Directory" -ForegroundColor Red


    ElseIf ($GroupMemberUsernames -contains $User) {

      Write-Host "$User already exists in AD Group X"


    Else {

      Add-ADGroupMember -id "ADGroupX" -members $User

      Write-Host "$User has been added to ADGroupX" -ForegroundColor Green
Until ($choice -eq 2)

The script inside switch option 1 works fine on it’s own, but when I run it as part of this switch and select Option 1 from the ‘Enter a number to continue’ screen, the script appears on the screen as though it has run but does not prompt for a Username. It just returns to ‘Enter a number to continue’.


Create a function with the code you have inside your switch statement at the moment and place the function definition before the switch statement. Then call the function from inside the switch statement. That should trigger your parameter section correctly I think.

A positive side effect would be that your code is much easier to read I think. :wink: