6

#PSTip Convert a path to WMI compatible path

Note: This tip requires PowerShell 3.0 or above.

Some of the WMI queries require that we specify the folder path with an escaped path separator. For example, take a look at the following error.

cimerror

So, we need to escape the path separator for the above query to work.

cimnoerror

When we are running such queries programmatically for user provided input, we need a better way to convert the path to WMI compatible path.

Here is the trick I use.

'C:\Windows' -replace "\\","\\"

How do you do it?

Filed in: Columns, Tips and Tricks Tags: , , , ,

6 Responses to "#PSTip Convert a path to WMI compatible path"

  1. Jeffery Hicks says:

    Or if your path comes from a variable defined elsewhere you could do something like this:

    $p=”c:windows
    get-wmiobject win32_share -filter “path=’$($p.replace(”,’\’))’”

  2. Martin Schvartzman says:

    I prefer using the [regex]::escape static method. for example:
    [regex]::Escape(“C:Windows”)

    • Ravikanth says:

      @Martin, you stole the thunder! :)
      That was the next tip I was writing in continuation to this. Thanks for sharing the idea with us and our readers!

      • Kirk Munro says:

        Be careful with that one. Regex has different escape characters than WMI/CIM, so using [regex]::Escape isn’t a safe practice to mix with WMI. For example, if you have a path with a “+” in it, then mixing [regex]::Escape with WMI/CIM queries will result in errors.

Leave a Reply

Submit Comment

© 2014 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: