I am coding in PowerShell 5.1 and have run across an odd issue when using Read-Host in a loop. For some reason, when I input something into Read-Host as per the code below, I always get it outputted on my PowerShell ISE console. Is there a way to flush the input buffer so that this doesn't happen?
Code:
function Test-Read{
for ($num = 1 ; $num -le 3 ; $num ){
Read-Host -Prompt "Test Prompt"
}
}
Output:
Test Prompt: a
a
Test Prompt: b
b
Test Prompt: c
c
Thanks, Aurora
CodePudding user response:
In PowerShell, all output from individual statements will "bubble up" to the caller (and eventually the screen buffer) unless suppressed or assigned.
Assign the string output from Read-Host
to a variable, or cast the results of the call to [void]
:
function Test-Read{
for ($num = 1 ; $num -le 3 ; $num ){
# $null is a special automatic variable - assigning to it won't affect it, much like piping to NUL in cmd or `/dev/null` on a UNIX/POSIX system
$null = Read-Host -Prompt "Test Prompt"
}
}
or
function Test-Read{
for ($num = 1 ; $num -le 3 ; $num ){
[void](Read-Host -Prompt "Test Prompt")
}
}