BenSBB
BenSBB

Reputation: 43

Stop a single quote from escaping a string in a WMI query powershell

I have some code which uses a WMI query, but i'm running into an issue where the variable i'm using has a ' (single quote), which causes the code to malfunction

Here is an example:

$path = "\\SERVER1\Mike O'Leary$"
$servername = $path.Split('\')[2].Split('\')[0]
$sharename = $path -replace ".*\\" -replace "'", "`'"
Get-WmiObject Win32_share -computer $servername -filter "name='$sharename'" | Select Name,Path

The problem is that the share name contains a ' character so it errors out. Paths without ' work fine

I tried using the replace seen above but this doesn't help

I've tried various combinations of quotes but I can't get it right, can anyone assist?

Thanks Ben

Upvotes: 3

Views: 2259

Answers (3)

Matt
Matt

Reputation: 46730

You need to escape that character in WQL. A blog that touches on this says you could escape it with a backslash.

$sharename = $path -replace ".*\\" -replace "'", "\'"

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

Use double quotes instead of single quotes in your filter string:

Get-WmiObject Win32_Share -Computer $servername -Filter "name=`"$sharename`"" | ...

The nested double quotes must be prepended with backticks to escape them inside the double quoted filter string.

Upvotes: 1

BenSBB
BenSBB

Reputation: 43

Oops, turns out I should've been using \ instead of `

$path = "\\SERVER1\Mike O'Leary$"
$servername = $path.Split('\')[2].Split('\')[0]
$sharename = $path -replace ".*\\" -replace "'", "\'"
Get-WmiObject Win32_share -computer $servername -filter "name='$sharename'" | Select Name,Path

Mystery solved!

Upvotes: 1

Related Questions