Disclaimer : I am the epitome of a scipting/Powershell rookie, so please bear with me.
I\'ve written a script to return the Active Directory username of any
Method 2 from the linked post - i.e., waiting for the user to press a key before exiting the script - can be used, but it requires additional effort:
End your script as follows in order to see the value of $list
before the pause
command prompts:
$list | Out-Host # Force *synchronous* to-display output.
pause # Wait for the user to press Enter before exiting.
Note: pause
in PowerShell is simply a function wrapper around Read-Host
as follows: $null = Read-Host 'Press Enter to continue...'
Therefore, if you want to customize the prompt string, call Read-Host
directly.
This answer explains why the use of Out-Host
(or Format-Table
) is necessary in this case; in short:
In PSv5+, an implicitly applied Format-Table
command asynchronously waits for up to 300 msecs. for additional pipeline input, in an effort to derive suitable column widths from the input data.
Because you use Write-Output
output objects without predefined formatting data that have 2 properties (4 or fewer ), tabular output is implicitly chosen, and Format-Table
is used behind the scenes, asynchronously.
Note: The asynchronous behavior applies only to output objects for whose types formatting instructions aren't predefined (as would be reported with Get-FormatData <fullOutputTypeName>
); for instance, the output format for the System.Management.Automation.AliasInfo
instances output by Get-Alias
is predefined, so Get-Alias; pause
does produce output in the expected sequence.
The pause
command executes before that waiting period has elapsed, and only after you've answered the prompt does the table print, after which point the window closes right away.
The use of an explicit formatting command (Out-Host
in the most generic case, but any Format-*
cmdlet will do too) avoids that problem by producing display output synchronously, so that the output will be visible by the time pause
displays its prompt.
I had the same problem for scripts that I'm executing "on demand". I tend to simply add a Read-Host
at the end of the script like so
$str = "This text is hardly readable because the console closes instantly"
Write-Output $str
Read-Host "Script paused - press [ENTER] to exit"