msgbartop
Everybody get your shell on!
msgbarbottom

Using command line variables with Powershell

Sometimes it is useful to be able to input a variable(s) when calling your powershell script. This creates some flexibility as far as automation, and also allows you to easily re-purpose your script without having to modify the actual script or update a text file. There are two standard methods for using command line variables.

The first method creating an array of input data and then setting a variable to that input later in your script. For instance, the way you would input these variables when calling your script would be:

PS .\test.ps1 var1 var2

…and the way you would capture those input parameters in your script would be:

1
2
$args[0] = $firstvariable
$args[1] = $secondvariable

The $args is a system variable which recognizes the input variables and selects one based on the array selection you choose. For instance $args[0] selects the first input parameter, which in this case is “var1″, and sets the variable $firstvariable to “var1″. $args[1] selects the second parameter, “var2″ in this case, and does the same thing. So on for $agrs[2], [3], etc.

The second way to accomplish this by using the PARAM() function. This allows you more control over what input parameters are being set, and ensures that the right values are being assigned to the correct variables. The way this looks like from the command line is:

PS .\test2.ps1 -firstvariable var1 -secondvariable var2

…and the way you capture that input in your script is by using the following function:

1
param($firstvariable,$secondvariable)

As you can see, by defining your desired variable names with the PARAM function, it gives you more control over the input and to what variable it is being assigned which drastically reduces the possibility of error. As an example, with the input parameter shown above, you could also call it this way:

PS .\test2.ps1 -secondvariable var2 -firstvariable var1

You noticed i switched the order of the variables. By using an array, as in the first example, it would simply have selected the first parameter, which would have been “var2″ now, and set it to $firstvariable, which wouldnt be desired. Using the PARAM function, since we are defining which variable each parameter is set to, this is not a problem.

  • Twitter
  • Facebook
  • LinkedIn
  • Digg
  • Google Bookmarks
  • Slashdot
  • StumbleUpon
  • Live
  • FriendFeed
  • Ping.fm
  • Print
  • email
  • PDF
  • RSS

Tags:

Reader's Comments

  1. |

    I downloaded a script that contains param and would like to automate and schedule instead of entering variables but do not know how. Where could i find this information?
    Thanks for listening!
    Alan

    Reply to this comment

Leave a Comment