Issue with Switch

Welcome Forums General PowerShell Q&A Issue with Switch

Viewing 1 reply thread
  • Author
    • #201969
      Topics: 1
      Replies: 0
      Points: 11
      Rank: Member

      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’.


    • #201975
      Topics: 5
      Replies: 2368
      Points: 5,986
      Helping Hand
      Rank: Community MVP

      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. 😉

      • This reply was modified 4 months, 4 weeks ago by Olaf.
Viewing 1 reply thread
  • The topic ‘Issue with Switch’ is closed to new replies.