Monday, February 11, 2013

Powershell Script DIY: Creating Variables

     The most important thing you do in Powershell scripting is setting variables.  A variable is any value that you need to refer to later.  It can be a location, a file name, a specific number, or anything you could possibly imagine! When done incorrectly, you can end up with a messy script that no one but the most attentive can step through.  Variables are always lead by a $, and can be any combination of letter and number characters.  While you can name your variable anything you want: $bobwehadababyitsaboy, its best practice to have a naming convention in place.  A naming convention is a standardized system of assigning names such as: FirstnameLastnamebirthyear or MakeModelYear.  These two examples would look like


Once you decide on a naming convention it is time to define your variable “foo.” We start with the $


And add the variable name:


Now a variable on its own is useless unless we assign a value, so we tell powershell that foo is equivalent to foo.txt in the current directory.  The = sign is used to say “is” and the quotation is to say “this value.” It is important to remember that the type of quotation is important as double quotes tell Powershell to treat the string as text and single quotes tell it to literally treat it as text.  To clarify, placing a variable in double quotes will return the value of the variable and single quotes will return the variable name as you typed it.:

$foo = “foo.txt”

Until you say otherwise, or close the session, the value of $foo is forevermore “foo.txt

As always, If you have a correction, or something to add, please post a comment below!

No comments:

Post a Comment