Passing a variable to a powershell script via command line

cquadrini picture cquadrini · May 7, 2013 · Viewed 324.7k times · Source

I am new to powershell, and trying to teach myself the basics. I need to write a ps script to parse a file, which has not been too difficult.

Now I want to change it to pass a variable to the script. that variable will be the parsing string. Now, the variable will always be 1 word, and not a set of words or multiple words.

This seems uber simple yet is posing a problem for me. Here is my simple code:

$a = Read-Host
Write-Host $a

When I run the script from my command line the variable passing doesn't work:

.\test.ps1 hello
.\test.ps1 "hello"
.\test.ps1 -a "hello"
.\test.ps1 -a hello
.\test.ps1 -File "hello"

As you can see, I have tried many methos with no success, of the script taking the value an outputting it.

The script does run, and waits for me to type a value, and when I do, it echos that value.

I just want it to output my passed in value, what minuscule thing am I missing?

Thank you.

Answer

Solaflex picture Solaflex · May 7, 2013

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)