Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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.

like image 662
Peanut Avatar asked Feb 05 '23 08:02

Peanut


2 Answers

The issue is that your script \.test.ps1 is not expecting the value.

Try this:

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):

Write-Host $input
like image 152
G42 Avatar answered Feb 06 '23 21:02

G42


You can't pipe input to Read-Host, but there should be no need to do so.

PowerShell doesn't support input redirection (<) yet. In practice this is not a (significant) limitation because a < b can be rewritten as b | a (i.e., send output of b as input to a).

PowerShell can prompt for input for a parameter if the parameter's value is missing and it is set as a mandatory attribute. For example:

function test {
  param(
    [parameter(Mandatory=$true)] [String] $TheValue
  )
  "You entered: $TheValue"
}

If you don't provide input for the $TheValue parameter, PowerShell will prompt for it.

In addition, you can specify that a parameter accepts pipeline input. Example:

function test {
  param(
    [parameter(ValueFromPipeline=$true)] [String] $TheValue
  )
  process {
    foreach ( $item in $TheValue ) {
      "Input: $item"
    }
  }
}

So if you write

"A","B","C" | test

The function will output the following:

Input: A
Input: B
Input: C

All of this is spelled out pretty concisely in the PowerShell documentation.

like image 43
Bill_Stewart Avatar answered Feb 06 '23 22:02

Bill_Stewart