The Big Book of PowerShell Gotchas
  • ReadMe
  • About this Book
  • Format Right
  • Where is the __ command?
  • PowerShell.exe isn't PowerShell
  • Accumulating Output in a Function
  • ForEach vs ForEach vs ForEach
  • Tab Complete!
  • -Contains isn't -Like
  • You Can't Have What You Don't Have
  • Filter Values Diversity
  • Not Everything Produces Output
  • One HTML Page at a Time, Please
  • Bloody. Awful. Punctuation.
  • Don't Concatenate Strings
  • $ Isn't Part of the Variable Name
  • Use the Pipeline, Not an Array
  • Backtick, Grave Accent, Escape
  • These Aren't Your Father's Commands
  • A Crowd isn't an Individual
  • Commands' Default Output Can Lie
  • Properties vs. Values
  • Remote Variables
  • New-Object PSObject vs. PSCustomObject
  • Running Something as the "Currently Logged-in User"
  • Commands that Need a User Profile May Fail When Run Remotely
  • Writing to SQL Server
  • Getting Folder Sizes
Powered by GitBook
On this page

$ Isn't Part of the Variable Name

PreviousDon't Concatenate StringsNextUse the Pipeline, Not an Array

Last updated 7 years ago

Big gotcha.

Can you predict what happened?

You see, the $ is not part of the variable's name. If you have a variable named example, that's like having a box with "example" written on the side. Referring to example means you're talking about the box itself. Referring to $example means you're messing with the contents of the box.

So in my example, I used $example=5 to put 5 into the box. I then created a new variable. The new variable's name was $example - that isn't naming it "example," it's naming it the contents of the "example" box, which is 5. So I create a variable named 5, that contains 6, which you can see by referring to $5.

Tricky, right? Comes up all the time:

In that example, I used the -ErrorVariable parameter to specify a variable in which I would store any error that would occur. Problem is, I used $x. I should have used x by itself:

That will store any error in a variable named x, which I can later access by using $x to get its contents - meaning, whatever error was stored in there.

image049.png
image051.png
image053.png
image055.png