Posted by: Richard Siddaway
PowerShell v2, WMI
String substitution is one of my favourite bits of PowerShell. If you’ve not seen it before the idea is that you can substitute a variable into a double quoted string. Note that single quote strings won’t work. As an example
PS> $colour = "red"
PS> "The balloon is $colour"
The balloon is red
PS> ‘The balloon is $colour’
The balloon is $colour
One place this breaks down in when substituting properties of an object. Consider something we’ve pulled back with WMI.
PS> $os = Get-WmiObject -Class Win32_OperatingSystem
SystemDirectory : C:\Windows\system32
BuildNumber : 7600
RegisteredUser : Richard
SerialNumber : 00426-065-1155216-86852
Version : 6.1.7600
We can pick off a couple of properties
PS> $os | select Caption, ServicePackMajorVersion | Format-List
Caption : Microsoft Windows 7 Ultimate
ServicePackMajorVersion : 0
We can use write-host
PS> Write-Host $os.Caption, $os.ServicePackMajorVersion
Microsoft Windows 7 Ultimate 0
and even expand it a bit
PS> Write-Host $os.Caption, "Service Pack", $os.ServicePackMajorVersion
Microsoft Windows 7 Ultimate Service Pack 0
but if we try string substitution
PS> Write-Host "The OS is $os.Caption with Service Pack $os.ServicePackMajorVersion"
The OS is \\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@.Caption with Service Pack \\RSLAPTOP01\root\cimv2:Win32_OperatingSystem=@.ServicePackMajorVersion
Oops – thats not what we want
The problem is that we are getting the object rather than the value. We need to use a subexpression
PS> Write-Host "The OS is $($os.Caption) with Service Pack $($os.ServicePackMajorVersion)"
The OS is Microsoft Windows 7 Ultimate with Service Pack 0
All this does is say give me the result of the expression in the brackets and substitute that in the string. Easy and neat. No need to concatenate strings to create the display line in your scripts.