Sunday, 9 July 2017

How to pass arguments to a powershell script?

It’s been a while folks. Recently, a colleague of mine asked me how to pass argument(s) to a PowerShell script and how does it work. I even come across the same problem when I started PowerShell so I decided to write something about it for those who may need.

Let’s dig into the subject:
Basically, you want to achieve something like this:

.\Powershell.exe “C:\myScript.ps1” -args1 “value1” -args2 “value2” […]  -optional1 -optional2 […]

With as many arguments and optional switch you want.

How it is done?


Edit your script and at the head of your file before everything add the following lines:


The statement:

Param(): declares parameters that will be used, pretty obvious.
[Parameter()]: specifications about the parameter if it is mandatory, its position …
[string] /[int] /[switch]: parameters type.


How does it work?


The variable provided in parameter can be called anywhere in your script.
Just remember one thing, the parameter “type”:
[String] means the value is casted into System.String and [Int] to System.Int32.
[Switch] is a little bit different. It doesn’t receive value like the others. It is a “Boolean”, If it’s specified its value is “true” and “false” otherwise.

How to use it?


The script can be called in two ways:

Specifying parameters:


Not specifying parameters:


In this case the “position” mentioned above is needed. This way the input is attributed to the correct argument of the script.

For example:

Here, name is associated with first value (this is what it means position=1), firstName with second value and so one.

If we run the code above, we will have:





Now let’s make some modification to the same script:

I just changed the Position value. And if we run it again, the output will be:






As you can see, the result is not the same, so when you write your script make sure to specify the correct position. 

The whole code


For those who are looking for a sample code: 

The output will be:

1) With no parameters specified:

2) With parameters specified:

Thanks for reading, hope it helped! 😊


Share:

0 commentaires:

Post a Comment

Popular Posts

Join us on Facebook

STATS

Contact Form

Name

Email *

Message *