Redirect standard input (read-host) to a Powershell script

Viewed 6844

Here's a sample powershell script:

$in = read-host -prompt "input"
write-host $in

Here's a sample 'test.txt' file:

hello

And we want to pass piped input to it from powershell. Here's some I have tried:

.\test.ps1 < test.txt
.\test.ps1 < .\test.txt
.\test.ps1 | test.txt
.\test.ps1 | .\test.txt
test.txt | .\test.ps1
.\test.txt | .\test.ps1
get-content .\test.txt | .\test.ps1

even just trying to echo input doesn't work either:

echo hi | \.test.ps1

Every example above that doesn't produce an error always prompts the user instead of accepting the piped input.

Note: My powershell version table says 4.0.-1.-1

Thanks

Edit/Result: To those looking for a solution, you cannot pipe input to a powershell script. You have to update your PS file. See the snippets below.

4 Answers

Yes; in Powershell 5.1 "<" is not implemented (which sucks)

so, this won't work: tenkeyf < c:\users\marcus\work\data.num

but,

this will: type c:\users\marcus\work\data.num | tenkeyf

...

PowerShell doesn’t have a redirection mechanism, but.NET have.

you can use [System.Diagnostics.Process] implements the purpose of redirecting input.

The relevant Microsoft documents are as follows.

Process Class

This is a sample program that works perfectly on my windows 10 computer

function RunAndInput{
    $pi = [System.Diagnostics.ProcessStartInfo]::new()
    $pi.FileName ="powershell"
    $pi.Arguments = """$PSScriptRoot\receiver.ps1"""
    $pi.UseShellExecute = $false
    $pi.RedirectStandardInput = $true
    $pi.RedirectStandardOutput = $true

    $p = [System.Diagnostics.Process]::Start($pi)

    $p.StandardInput.WriteLine("abc"+ "`r`n");
    $p.StandardOutput.ReadToEnd()
    $p.Kill()
}

RunAndInput

# OutPut

Please enter the information: abc
Received:abc

# receiver.ps1
('Received:' + (Read-Host -Prompt 'Please enter the information'))

Hope to help you!

Related