Question:
Here’s a sample powershell script:
1 2 3 |
$in = read-host -prompt "input" write-host $in |
Here’s a sample ‘test.txt’ file:
1 2 |
hello |
And we want to pass piped input to it from powershell. Here’s some I have tried:
1 2 3 4 5 6 7 8 |
.\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:
1 2 |
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.
Answer:
The issue is that your script \.test.ps1
is not expecting the value.
Try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
param( [parameter(ValueFromPipeline)]$string ) # Edit: added if statement if($string){ $in = "$string" }else{ $in = read-host -prompt "input" } Write-Host $in |
Alternatively, you can use the magic variable
$input
without a param
part (I don’t fully understand this so can’t really recommend it):
1 2 |
Write-Host $input |