Refactored Codes
How to define parameters in a powershell script, and pass the values from command line
Hey There!!! Today, we will learn - How to define parameters in a powershell script and pass those as arguments from Command line. You can watch the video version here. [embed]https://youtu.be/UntfWMYOlmk[/embed] First we create a very basic script.
Write-Output "My Name is Anurag Anand, and I am 33 years old."
Ok, we have our basic script ready, save it with a file name of your choice, with .ps1 extension. eg. about-me.ps1 If you run in now, it will print the string in double-quotes. In the above script the firstname, lastname and age is written as the part of the script code. We can make this script work for everyone, by reading the data from the user, where user can provide the values for firstName, lastName and Age from command line. So, let us add the parameters to the script. We will define three parameter one for each data points. 1. First Name 2. Second Name, 3. Age After adding the parameters, the new script looks like.
param( [string]$FirstName, [string]$LastName, [int]$Age)

Write-Output "My name is $FirstName $LastName, and I am $Age years old."
To Define the parameters, we use param clause with parameter names separated by comma and surrounded by paraentheses. The datatype is provided in the square bracket. The name of the parameter starts with $ sign. param( [string]$FirstName, [string]$LastName, [int]$Age) So, the above line defines, a $FirstName, $LastName, $Age variables, and [string] and [int] are data-types of those variables. To run the script , provide the path to the script and values of each parameter.
.\about-me.ps1 -FirstName Anurag -LastName Anand -Age 33;
And, after hitting Enter, We get the following output. Powershell script executed with arguments for first name, last name and age. This concludes this section. Thank you for reading it.