Saturday, September 5, 2020

PowerShell: Expanding Object Properties in Strings using Subexpression Operator

Expanding variables inside a double quoted string is useful as shown below but this approach works with variables and not with object properties:

[string] $hostName = 'Executive Officer Kane'

Write-Output "Host name: $hostName"

The output from the above script snippet is as follows:


The script below expands object properties using the subexpression operator in a string that is passed to the Write-Host cmd-let (see the last line of code, Write-Host, in the script below):


The subexpression operation, $(), means that code in the parenthesis is invoked first hence the property is evaluated and then expanded in the string:

"Orphaned $($nic.Name) $($nic.resourcegroupname)"

The subexpression operator is documented in About Operators as follows:


Double quoted strings are useful for variable and object/property expansion but recall the previous post PowerShell: Use Single Quotes Where Possible,



No comments :

Post a Comment