Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a variable to a powershell script via command line

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.

like image 688
cquadrini Avatar asked Sep 26 '22 20:09

cquadrini


People also ask

How do you pass variables in a PowerShell script?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

How do I pass a variable in command prompt?

To pass variable values via the command line, use the PrjVar ( pv ) or PSVar ( psv ) arguments for the project and project suite variables respectively. Variable values you pass via the command line are temporary.

How do I pass a command line argument in PowerShell?

Powershell will process and assign the arguments in the order they're given, unless overridden by using the proper parameter name, e.g., if your param block lists: $user $pass $server, and you execute yourscript. ps1 a b c, a will be set into $user, b into $pass and c into $server, UNLESS you specifically assign them!


2 Answers

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)

like image 74
Solaflex Avatar answered Oct 16 '22 12:10

Solaflex


Here's a good tutorial on Powershell params:

PowerShell ABC's - P is for Parameters

Basically, you should use a param statement on the first line of the script

param([type]$p1 = , [type]$p2 = , ...)

or use the $args built-in variable, which is auto-populated with all of the args.

like image 56
Brian Stephens Avatar answered Oct 16 '22 12:10

Brian Stephens