Advanced Windows PowerShell Scripting Video Training

Advanced Windows PowerShell Scripting Video Training
Advanced Windows PowerShell Scripting Video Training

Wednesday, March 26, 2014

How long can a variable name be in PowerShell?

Well, that is a good question.  Before I answer this, let’s just cover a few best practices when it comes to naming variables.

  • Choose a variable name that gives you an idea of what is stored in the variable.
  • Use letters, numbers, and “_” in your names.
  • Do not use spaces.  They really make things look bad.

Now, about how long can they be?  I wrote a little function to help be create long strings of random characters and the I used that string as the name of my variable.

Function New-String

{

Param ($Length)

 

    $String = ""

    For ($X=0;$X -lt $Length; $X++)

    {

        $String += [char]((Get-Random(26))+65)

    }

    Write-Output $String

}

New-String 10000

 

I copied this string into memory.  I then typed a dollar sign and pasted this string.  Automatic carriage returns were added by the ISE so I had to go to the end of the string and press Delete a few times to get it all back on the same line.  I then added = “Hello”.  Below is a screen shot of my ISE.  Take notice of the column number.

 

image

 

I pressed enter and it accepted it.  I hit the up arrow and removed ‘'= “Hello” and pressed enter.   The contents of the variable dumped to the host.  In short, you can go up to 10,000 characters and more in a variable name.

The Variable drive truncates it when you look at it.

image

Should you do this???  Absolutely not.  This is just an exercise to show you that you do not have to worry about the length of a variable.  You just need to make sure it makes sense and is readable to others who may view your code.

No comments: