Home > Net >  PowerShell string interpolation not working
PowerShell string interpolation not working

Time:01-16

I'm starting to learn powershell scripting and I'm getting stuck on a simple problem (surely due to my inexperience): string interpolation.

I'm trying to print a list of directories that I'm obtaining with the Get-ChildItem cmdlet. I've read in tutorials that to output a property of an object inside a string you should use "${$variable.property}", so I tried with this code:

foreach($pluginDir in Get-ChildItem -Path "./Plugins" -Directory){
    Write-Host "Found plugin directory ${$pluginDir.FullName}"
}

The Get-ChildItem command is working correctly (I've tried by printing $pluginDir.FullName directly without interpolating it inside the string), however the string interpolation is not. All I get in the output from the above code is:

Found plugin directory
Found plugin directory
Found plugin directory
...

what am I doing wrong here?

CodePudding user response:

The correct syntax would be:

Write-Host "Found plugin directory $($pluginDir.FullName)"

More on command substitution: https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-string-substitutions?view=powershell-7.3#command-substitution

  • Related