Search code examples
powershellread-host

Why is the "Read-host" section running before the code?


I just wanted a .ps1 file that will run a simple line of powershell but not close instantly.

Ive tried to do "read-host -prompt " " " but it is displaying before the code is run and then still closes instantly

get-appxpackage -allusers | select name 

read-host -prompt "Press enter to exit"

I expect the outcome to be I run the file and then get a chance to read the output within the powershell window before pressing something to exit. But the actual output is prompts to exit before the code is run and then it runs through the output and closes


Solution

  • After executing this line of code:

    get-appxpackage -allusers | select name 
    

    You'll have some "pending" objects ready to return to the Powershell pipelines output stream. The objects can't be sent to the pipeline until Read-Host has finished (since Powershell will treat these objects as "output" of your ps1 file). After Read-Host has finished the objects are sent to the pipeline (via the output stream). Since there is no other cmdlet there (using the output of you ps1 file), Powershells default behavior is to output the pipeline content to the Powershell host.

    As @Lee_Daily already mentioned in above comment, adding Out-Host will send the output of get-appxpackage -allusers | select name to the Powershell host. So get-appxpackage -allusers | select name | out-host no objects are queued in the output stream for further pipeline actions.

    I would recommend you check following sources:

    These are essential Powershell concepts you've to understand.

    Hope that helps.