do-while loop not printing results after first iteration

Welcome Forums General PowerShell Q&A do-while loop not printing results after first iteration

This topic contains 2 replies, has 2 voices, and was last updated by

1 week ago.

  • Author
  • #176749

    Topics: 1
    Replies: 1
    Points: -6
    Rank: Member

    Hello everyone,

    Attempting to learn PowerShell and I have run into an issue that I really can't find the solution to in other forms (at least using my search terminology) so if this topic exist please feel free to point me in that direction.


    My issue is that I have a very simple "do-while loop", however, it does not print the output of the Get-ADPrincipalGroupMembership query on the first iteration. For example, I run the script and enter a username then click enter. Instead of my expected result which is print the memberships, it loops around and asks for username again without printing the results of the first inputted username. Once I enter the username the second time in the loop and click enter then it prints the results of the first input and the results of the second input. Any time after the second iteration the script works fine and actually prints the results correctly after I provide the input. Below is the script in question.


    The code below is simply supposed to ask the user for a username then run a query in AD to list the memberships of a given user. After providing the memberships of a user the script should ask for another user and repeat the process until the user enters "exit" and the script exits out.


    do {
    $user = Read-Host -Prompt 'Enter the username of the user' 
    Get-ADPrincipalGroupMembership $user | select name;
    } while ($user -ne 'exit');
    stop-process -id $PID;

    Any help would be appreciated. Thank you, everyone

  • #176797

    Topics: 1
    Replies: 1529
    Points: 2,587
    Helping Hand
    Rank: Community Hero

    Sometimes Powershells output optimization overoptimizes the output. You could add an " | Out-String " after the " | select name " ... and btw – you don't need to use a semicolon at the end of each line in Powershell. That's only needed when you want to write more than one command on one line. 😉

  • #176827

    Topics: 1
    Replies: 1
    Points: -6
    Rank: Member

    Hello Olaf,

    Amazing !! Thank you for your quick reply. Also, thank you for the tip regarding semicolons. Syntax has played out to be my biggest hurdle considering that my background is in software development which semicolons are used everywhere. Once again Thank you for your assistance I really appreciate it.


    Robert Martinez

You must be logged in to reply to this topic.