Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PowerShell Read-Host outputting input to console

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Test Prompt: a
a
Test Prompt: b
b
Test Prompt: c
c

Thanks,
Aurora

>Solution :

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")
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading