Wednesday, November 29, 2006

Variables and types

A variable in PowerShell must begin with the dollarsign ($). The name of the variable stops at the first word breaking character (such as space, comma or period). If special characters are needed in a variable, name curly braces can be used to surround the variable name:

$myvar = "normal variable name"
${ugh!b££!!¤&(} = "special variable name"

In order to determine the type of a variable, the GetType method can be used:

$a = 1234
$a.GetType() ## Displays the type of $a

$b = "1234"

[int]$c = $b ## casts $c as an integer (int32)

To get information of properties and methods of a given object - in this case a variable - use Get-Member -InputObject.
Notice the difference between the string variable $b and the integer cariable $c

Get-Member -InputObject $b
Get-Member -InputObject $c

Examples - using various methods on a variable:

$d = "Hello world! I'm back again!"

1 comment:

Jeffrey Snover said...

Be aware that when you use
you can put any charactes you want in the braces however ":" has special meaning. When PowerShell sees a ":" in ${}, it treats the variable as a PATH and uses it to store the variable. In other words:
PS> ${c:\foo}=5
PS> dir c:\foo

Directory: Microsoft.PowerShell.Core\FileSystem::C:\

Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 11/29/2006 6:41 AM 3 foo

PS> cat c:\foo

Pretty cool!
Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at:
Visit the Windows PowerShell ScriptCenter at: