Working with Variables

Variables

There are a number of handy variables which you can see at about_Automatic_Variables, however Introduction to Microsoft PowerShell – Variables is an excellent article to get a good overview and learn interesting tricks like:
dir variable:
Turns out the variables are loaded into a PowerShell drive like the Windows Registry and the File System.

As is often the case Kevin Marquette has written an excellent article Powershell: Everything you wanted to know about variable substitution in strings which is a very good read.

See the following for more information:

Environment Variables

I suggest you just read Windows PowerShell Tip: Creating and Modifying Environment Variables not much value I can add to that! However, if you want to get the value of the logonserver environment variable you can do this with $Env:logonserver, which is nice and easy. You might also want to read Windows PowerShell Cookbook - View and Modify Environment Variables.

Defining Variables

You can define a variable in two different ways, as follows:
$var1 = 100
Set-Variable var2 200

In both these cases the values are changeable. You can make a variable read-only like this:
Set-Variable -Option ReadOnly var3 300
Then if you try to change the value you get an exception. However you can delete the variable and re-create it, although removing requires the use of the "force" option as seen in the following example:
Remove-Variable -Force var3

Defining Constants

If you want to create a real constant that cannot be changed or remove, even with a force, then you need this:
Set-Variable -Option Constant var4 400
Set-Variable -Option Constant -Name var4 -Value 400

Type Information

To display full type information of a variable use one of the following:
$var.GetType()
$var.GetType().FullName
Where the first gives you all the type iformation and the second the complete type name, which is useful for testing for a type, which is done as follows:
if ($var -is [System.DateTime]) ...