2

In a Linux shell script called hello.sh for example, you can take input in the following manner:

$name = $1
$Age = $2

echo "Hi $name!"
echo "You are $age years old!"

And one would execute this script on the Linux command line as the following:

./hello.sh Bob 99

Is there an equivalent way to take input in the script in PowerShell in this manner?

I have only seen Read-Host, but this prompts the user for input after the Powershell script has executed. I would like to call the script with the required input parameters on the command line.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Index Hacker
  • 2,004
  • 3
  • 17
  • 20

2 Answers2

4

Yes, here is a parameterized script:

[CmdletBinding()]
param (
      [string] $Name
    , [int] $Age
)

Write-Host -Object "Hi $Name!","You are $Age years old!";

Then, to call the script:

.\test.ps1 -Name Trevor -Age 28;
  • Thanks for the response! Is there a way to take input and not have to indicate the variable types like in linux? – Index Hacker Jul 04 '14 at 18:38
  • Yeah, you don't have to declare named parameters, if you don't want to. You can use `$args[0]` and `$args[1]` instead. :) –  Jul 05 '14 at 18:13
1

Another option that is perhaps more similar in nature to the Linux example is:

$name = $args[0]
$Age  = $args[1]
echo "Hi $name!"
echo "You are $age years old!"

I am just trying to show the gap isn't so great here. Note: echo is an alias for Write-Output. Folks tend to prefer to use that over Write-Host whose output can't be captured or redirected.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Keith Hill
  • 194,368
  • 42
  • 353
  • 369