Introduction
I was very curious about the Windows PowerShell Pack library and tried to understand some of the WPK concepts. Reading some of its script source code I came across a strange looking use of the colon punctuation character. As I found out later, it was used for explicit value passing to a switch parameter of a function. I thought it is time to write a blog post about all these different occurrences of the colon character in PowerShell.
Figure 1: I Spy a colon
There are three different uses of the colon in PowerShell:
Static or shared members of .NET classes
The first type of occurrence of the colon denotes the de-referencing of a static or shared member of a .NET class. Be aware that the type names can be stored in a PowerShell variable. Here are examples of this case.
Figure 2: Uses of colon to access static class members. How many colons do you spy?
$CurrentTime = [DateTime]::Now
$CurrentTime
$Tokens = "This", "is", "a", "list", "
;of", "tokens"
$Tokens
$StringOfTokens = [String]::Join(" ", $Tokens)
$StringOfTokens
$DateTimeType = [DateTime]
$DateTimeType::Now
Variables in Global or Script Scope
The second use of the colon character is to specify the scope of a variable. If variable names in different scopes are shadowing each other than the scope identifiers help explicitly referring to the correct instance of a variable.
Figure 3: Uses of colon to specify the scope of variables. How many colons do you spy?
$C = 100
function Increment()
{
$C = 10
1..10 | Foreach-Object `
{
$C++
$Script:C++
$Global:C++
}
$C
$Script:C
$Global:C
}
Increment
20
120
120
Switch Parameters
The third use and to me the one I didn’t know about before is for explicitly forwarding switch parameter values from one function to another.
Figure 4: Uses of colon to explicitly pass values to a switch parameter. How many colons do you spy?
function BurnCPU([switch] $IRealyMeanIt)
{
if( $IRealyMeanIt){"Do it"} else {"Just kidding"}
}
$Answer = Read-Host "Do you realy mean it? (Y/N)"
if($Answer -eq "Y") {$Decision = $True }
elseif($Answer -eq "N") {$Decision = $False }
BurnCPU -IRealyMeanIt:$Decision
Download
The PowerShell script files used in this article can be downloaded here: UseOfColonInPowerShell.zip
Contest
How many : colon (punctuation) characters do you count in this blog post? The answer is not quite obvious. Here are some things to consider:
- Count all colons in the pictures
- Count the (one) most obvious colon that is hidden in the title picture
- Count all colons in the text of this post
- Count horizontal colons, like this one “..” (The example counts as well).
- Only count colons that are in this white box that enclosed this blog post. Don’t count any in the rest of this page.
The first reader who posts the correct answer as comment is going to win a free PDF e-book of PowerShell In Action 2.0.
Offer ends 12/31/2009. Restrictions apply.