0

I'm new in learning Powershell and I ran into a problem that makes me go insane. I want to write a simple Powershell script, that can be used to get both the group memberships of certain ActiveDirectory users, and the users of certain ActiveDirectory groups, and in the end gives the option to write the result on the console, or save it as csv. Everything works perfectly fine, except no matter what I do, I can't stop the window from closing right after it writes the results on the console. I know that I can run a PS1 from command line in a way that doesn't allow the window to close, but I'd like Powershell do it by itself.

I tried to use both "pause" and Read-Host after the query script, but the stop event always happens BEFORE the result gets out on the console, no matter what's the order between the two of them. I simply cannot understand why the order of the execution of the two commands is backwards. Could you give me some insight why Powershell does it?

$nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"
Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select @{n='Name'; e='name'}, @{n='Description'; e='description'}, @{n='Username'; e='samAccountName'}
$temp = Read-Host "Press Enter to continue..."
sgtGiggsy
  • 65
  • 9
  • 3
    Possible duplicate of [Output of a PowerShell command doesn't show result until after Write-Host and Read-Host](https://stackoverflow.com/questions/47359808/output-of-a-powershell-command-doesnt-show-result-until-after-write-host-and-re) – Robert Dyjas Mar 28 '19 at 13:34
  • To prevent the PowerShell window from closing look at [this](https://stackoverflow.com/questions/24546150/how-can-prevent-a-powershell-window-from-closing-so-i-can-see-the-error) – jrider Mar 28 '19 at 14:03

1 Answers1

0

So you need to explicitly tell powershell to output the string. I also added in some error handling for you, so you don't have to run the script every time. Like if the group was typed wrong or doesn't exist.

Do
{
    $nameofgroup = Read-Host -Prompt "`nPlease enter the name of the group!`n"

    try
    {
        Get-ADGroupMember -identity $nameofgroup | Get-ADObject -Properties description, samAccountName | select @{n='Name'; e='name'}, @{n='Description'; e='description'}, @{n='Username'; e='samAccountName'} | Out-String
        $errorMessage = 'False'
        Read-Host -Prompt 'Press Enter key to exit'
    }
    catch
    {
        Write-Host "Could not find group please try again"
        $errorMessage = 'True'
    }
}
while($errorMessage -eq 'True')
SysEngineer
  • 354
  • 1
  • 7