bornfromanegg
bornfromanegg

Reputation: 2928

Variable expansion in Powershell Where-Object cmdlet

In the following script:

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | where {$_.DisplayName -like '*Visual*' } | Select-Object -ExpandProperty DisplayName

$productName="Visual"
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | where {$_.DisplayName -like '*$productName*' } | Select-Object -ExpandProperty DisplayName

the first Get-ItemProperty returns the correct results, the second returns nothing.

I tried using a ScriptBlock:

[ScriptBlock]$whereClause = [ScriptBlock]::Create("$_.DisplayName -like '*$productName*'")

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | where $whereClause | Select-Object -ExpandProperty DisplayName

but this errors with "The term '.DisplayName' is not recognized as the name of a cmdlet...."

I've tried various other variations, but I can't seem to get it working and I'm not sure what I'm missing. I would like to be able to use a parameter variable in the Where-Object cmdlet. How do I do this?

Upvotes: 0

Views: 386

Answers (1)

Avner
Avner

Reputation: 4556

You're trying to use string interpolation with a string constant:

'*$productName*' is a string constant. To use string interpolation in powershell you need to use double quotes:

"*$productName*"

Upvotes: 0

Related Questions