Archive for November, 2012

Powershell, environment variables, ps-providers and variable scopes

When retrieving values of environment variables in Powershell the following syntax is valid


I started thinking about this. What is the underlying principle that allows for this syntax? It looks like env is a variable scope here in the same way as global, local, script and private can be used to reference variables in different scopes (along with numbered scopes):

$global:variable-name, $local:variable-name, $script:variable-name, $private:variable-name

When running “get-help about_scopes” we can find out that global, local etc are called scope modifiers but nothing tells us about env. It seems like we have reached the end of the road here. How can we grok this? Lets think about other ways to access environment variables. Powershell has a psdrive for enviroment variables which means that we can do the following:

get-content env:variable-name

This is interesting. Almost the same syntax appear here except for the $-sign. Let’s test the following hypothesis;

“$ps-drive-name:item-name is equivalent to get-content ps-drive-name:item-name

$-syntax ps-drive syntax equivalent?
$function:function-name get-content function:function-name yes
$variable:variable-name get-content variable:variable-name yes
$alias:alias-name get-content alias:alias-name yes

This seems to make sense. But does this really work for files too…? If it is true then the following would be possible to get the content of a file:


But this does not work. Why? Is the hypothesis wrong? No. It just turns out that this syntax does not handle the dot symbol without special care. It turns out that we have to write


to get the content of myfile.txt. The syntax works if the file has no special characters, such as:


But wait! The $-syntax suggests that we are dealing with variables. Why cant we set file content using this syntax:

$c:myfile = “new content”

And indeed we can! I love the fact that the creators of Powershell did not choose to add a special case just to handle environment variables. Happy days.

Categories: Uncategorized