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"
$myvar
${ugh!b££!!¤&(} = "special variable name"
${ugh!b££!!¤&(}

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"
$b.GetType()

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

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!"
$d.Split()
$d.ToLower()
$d.ToUpper()

1 comment:

Anonymous 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
5

Pretty cool!
Enjoy.
Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx