PowerShell Tip: Scoping Script Execution

By Michael Flanakin @ 8:43 AM :: 1311 Views :: Digg it!

PowerShell

PowerShell gives us three different ways to execute scripts.

  • func()
  • &func()
  • . func()

I learned this one a while ago and have to say it was pretty annoying... at least before I knew what was happening. Most people expect the first type of execution, because it's used in any scripting or programming type of environment. The other two seemed odd to me, tho, and I would never have known about it if someone didn't tell me why I was having issues with a script. Oh, and there doesn't seem to be anything in the built-in help about it.

The difference between these three is all about scope. Let's start with an example script.

$x = "123";
function setX($value) { $x = $value; "x = $x"; }
setX("xyz");
$x;

What do you think will happen? Will $x be "123" or "xyz"? The answer is "123". Why? Because, by default, script blocks are entirely self-contained.

Now, let's use the "&" to see what happens -- remember that $x is still "123".

&setX("xyz");
$x;

What now? Same thing. It's still "123". The main purpose of the "&" prefix is to allow you to execute something. This could be a function, like we did here, or it could be a file name. This allows you to build a string or get a file name and then use something like &$docxfile to open the file in the default program.

Finally, we have the "." prefix, which I'm sure you can guess what will happen. The only thing you have to remember is to put a space between the "." and function name. Again, $x is still "123".

. setX("xyz");
$x;

Finally! Our variable has changed.

For a bit of background, I ran into this when trying to re-run my profile script. I was aware of the "&" execution prefix and tried &$profile to re-run my profile. It worked, but the new functions I added to it weren't available to me. I went thru several work-arounds to make them available before manning-up and asking what the deal was. Actually, I did try using the "." prefix, but I tried .$profile, which didn't work. This was because I didn't put a space between the "." and the function (or file name, in my case).

Ratings