PowerShell for Windows Admins

May 4 2010   3:07PM GMT

String Substitution with WMI

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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
PS> $os

SystemDirectory : C:\Windows\system32
Organization    :
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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: