Index Hacker
Index Hacker

Reputation: 2024

PowerShell equivalent to Linux for user input

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.

Upvotes: 2

Views: 3388

Answers (2)

Keith Hill
Keith Hill

Reputation: 201812

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.

Upvotes: 2

user189198
user189198

Reputation:

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;

Upvotes: 4

Related Questions