Reputation: 2868
I was looking over what's coming with the next WinRM and PowerShell 3 and I was looking through the list of breaking changes and saw something that I'd never seen before.
The example was:
$server = "msp42"
$status = "online"
"$server: $status"
The resulting output was:
online
OK, I'd never encountered that before and have no clue why the colon caused an issue. A solution suggested in the document was to put a space (which is silly because then you change the output):
"$server : $status"
Another suggestion was to use this format (new to me!):
"${server}: $status"
The final suggestion was to make an expression, which I am familiar with and use all the time:
"$($server): $status"
So, my questions to you PowerShell gurus out there are:
What the heck is up with that colon? Does it do something?
What the heck is the ${variable}
syntax? Is it strictly to deal with the colon or does it have some neat features?
Upvotes: 44
Views: 46955
Reputation: 354576
The colon is a valid character for variable names, e.g. in $Env:PATH
, etc.
You can use the following option, too
$server`: $status
or, for some cases a format string is more readable:
'{0}: {1}' -f $server, $status
Back to the colon. There is a special case for variable names that correspond to an item on a PSDrive:
$Env:Foo # equivalent to the contents of Env:\Foo
$Function:C: # equivalent to the contents of Function:\C:
${C:\autoexec.bat} # ... you get the picture
The syntax ${}
exists to be able to specify variable names that otherwise use characters reserved for other parts of the syntax. You could see it as being similar (but more powerful) to C#'s @
in front of identifiers. See above where a \
is used in the variable name, since $Drive:Item
only works for the current container on a drive (or the root for non-hierarchic ones like Env
, Alias
or Function
).
Another example where the variable name would be normally invalid syntax:
PS> $+
The term '$+' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ $+
+ ~~
+ CategoryInfo : ObjectNotFound: ($+:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
PS> ${+} = 5
PS> ${+}
5
PS> Get-Variable +
Name Value
---- -----
+ 5
Upvotes: 66