1

ISSUE:

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.

EXPECTED RESULT:

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.

CODE SNIPPET:

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

Stop-Process -Id $PID;
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
CobraTech
  • 45
  • 9

2 Answers2

1

Just got an answer form anther forum. The simplest solution to this is to simply add "| Out-String" after "| select name". The updated example is below.

do {
$user = Read-Host -Prompt 'Enter the username of the user' 
Get-ADPrincipalGroupMembership $user | select name | Out-String
} while ($user -ne 'exit')

stop-process -id $PID
mklement0
  • 382,024
  • 64
  • 607
  • 775
CobraTech
  • 45
  • 9
  • Your answer is effective, but it's worth explaining why that workaround is necessary - please see the [linked post](https://stackoverflow.com/a/43691123/45375). In short: `... | select name` displays _asynchronous_ display behavior; piping to `Out-String` forces _synchronous_ display. – mklement0 Sep 13 '19 at 16:29
0

The property Name is an object from type string:

name              Property              System.String name {get;}

So you may simplify a bit:

do {
    $user = Read-Host -Prompt 'Enter the username of the user' 
    (Get-ADPrincipalGroupMembership -Identity $user).name
} while ($user -ne 'exit')

stop-process -id $PID

Best regards, Ivan

Ivan Mirchev
  • 829
  • 5
  • 8
  • While this accidentally bypasses the OP's problem too, the problem was not with _what_ (the format of the output), it was with _when_ (the fact that output happened _asynchronously_ and didn't appear when expected) - please see [the linked post](https://stackoverflow.com/a/43691123/45375). – mklement0 Sep 13 '19 at 16:31