Author Posts

November 11, 2015 at 10:23 am

How do you wrap a variable into a search query and have the variable be a wildcard?
$PCName = Read-Host -Prompt "Enter PC Name: "
$searchterm = Read-Host -prompt "Enter search term: "
Invoke-Command -Computername $PCName {Get-WmiObject -Class Win32_Product | Where-Object "name -like '%$searchterm%'" | FT IdentifyingNumber, Name, LocalPackage}

I've tried a number of things, but nothing is working.

November 11, 2015 at 11:51 am

Couple of issues here.

Number 1 don't use read-host for input. Create a function and make the computer and filter parameters

More importantly you're mixing wildcards
% is the wildcard when you're using WQL or a WMI filter
* is the wildcard when you're using strings in where-object

Your filter shouldn't be in quotes so looks like this

Where-Object name -like "*$searchterm*"

With WMI you can filter at the same time as getting the data – much faster so your code should look like this

$computername = $env:COMPUTERNAME
$filter = 'Live'
$scriptblock = {
param($filter)
Get-WmiObject -Class Win32_product -Filter "Name LIKE '%$filter%'" |
Select IdentifyingNumber, Name, LocalPackage }
Invoke-Command -ComputerName $computername -ScriptBlock $scriptblock -ArgumentList $filter

Use the -Argumentlist parameter on Invoke-command to pass the filter to Get-WmiObject.

You use the computrename parameter on Get-WmiObject or better still Get-CimInstance which would simplify the code

Get-WmiObject -Class Win32_Product -ComputerName $computername -Filter "Name LIKE '%$filter%'" | Select IdentifyingNumber, Name, LocalPackage

Get-CimInstance -ClassName Win32_Product -ComputerName $computername -Filter "Name LIKE '%$filter%'" | Select IdentifyingNumber, Name, LocalPackage