2

I'm trying to send parameters to the PowerShell script using pipes.

If I use standard function 5 | echo everything is ok. But when I replace standard echo with my script myecho.ps1 5 | myecho.ps1 no results are shown.

This is myecho.ps1 script.

param([string]$str)

echo $str

How can I send parameters to myecho.ps1 script using pipes?

1

2 Answers 2

3

You have to specify that $str can take value from pipeline (I also added Mandatory parameter here - it's not necessarily needed, but fits well into that specific script):

param(
  [Parameter(Mandatory=$true,
  ValueFromPipeline=$true)]
  [string]
  $str
)
echo $str

Then you invoke that script and it should work (remember about .\ before file name):

PS> "a" |.\myecho.ps1
a

You can learn more about advanced parameters using Get-Help about_Functions_Advanced_Parameters or in it's online version.

Sign up to request clarification or add additional context in comments.

Comments

3

You can specify further attributes for the parameters in PowerShell, look at MS documentation about Parameter Attribute Declaration.

In your case you should set the attribute valuefrompipeline to $true.

Use this code for parameters you want to pass by pipeline.

param(
    [parameter(ValueFromPipeline = $true)]
    [string]$str
)

NOTE You can use pipeline in PowerShell by 2 ways, "ByValue" and "ByPropertyName", i recommend you to take a look here to better understand the difference between them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.