3

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

BenSBB
  • 43
  • 5

3 Answers3

2

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 "'", "\'"
li ki
  • 342
  • 3
  • 11
Matt
  • 45,022
  • 8
  • 78
  • 119
1

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!

BenSBB
  • 43
  • 5
1

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.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328