do-while loop not printing results after first iteration

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

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. :wink:

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