Interpolation in PowerShell

Interpolation is PowerShell is a way to connect the strings with variables without concatenation. Interpolation allows you to expand the variables within the string type declarations and outputs during runtime.

For example: Look at the code below for a number given by the user. If you want to print the number given by the user, you can do something like the below using concatenation.

$ChosenNumber = 30
Write-Host "ChosenNumber is: "$ChosenNumber
Output:
ChosenNumber is:  30

PowerShell and many other scripting languages support string interpolation, where you can populate the values without concatenation. One thing you need make sure is, that you are using the double-quotes (“”) when you want to apply the interpolation. The single quote make the given value as string by suppressing it’s value that get populated.

There are various ways to implement interpolation and let us see some of the examples. Consider the ChosenNumber is 30. and you can give any values i.e. string, array, etc.

$ChosenNumber = 30

#Example-1

Write-Host "ChosenNumber is: "$ChosenNumber

Output:
ChosenNumber is:  30

#Example-2: Interpolation
Write-Host "ChosenNumber is: $ChosenNumber"
Output:

ChosenNumber is:  30

#Example-3: With Single Quote
Write-Host 'ChosenNumber is: $ChosenNumber'

Output:
ChosenNumber is: $ChosenNumber

# Example-4: Multi-Line
 interpolation

$Str = @"
    ChosenNumber is: $ChosenNumber
"@
Write-Host $Str

Output: If you simple type $Str on Console, you will see something like below:
ChosenNumber is: $ChosenNumber
but if you use any command that uses the Str such as Write-Host below:
Write-Host $Str, then the output would be:
ChosenNumber is:  30

The values get populated during the runtime. 

#Example-5: Multi-Line single quote
$Str = @'
    ChosenNumber is: $ChosenNumber
'@
Write-Host $Str
output:
ChosenNumber is: $ChosenNumber


# Example-6: Handling Objects
$Process = Get-Process -Name powershell

Write-Host "ProcessName is: $($Process.ProcessName)"

Output:
ProcessName is: powershell

Note: When you want object properties to be displayed on Sonsole, then you need to surround the Object and it's property with $() to read the property. If you dont use, then the process hadler and name will be displayed as below
Write-Host "ProcessName is: $Process.ProcessName"
Output: 
ProcessName is: System.Diagnostics.Process (powershell).ProcessName

# With single quote
Write-Host 'ProcessName is: $($Process.ProcessName)'
Output:
ProcessName is: $($Process.ProcessName)

Share your love

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Leave a Reply

Your email address will not be published. Required fields are marked *