Escaping paths with backslashes, single quotes and double quotes in WMI WQL in C#

So we've started digging back into our very old WMI support functions. Given that most of our code now uses PowerShell remoting these have been left in the dark for a while but we thought it was time to refresh them given our Windows agent always falls back on WMI when PowerShell remoting isn't available....

And we still have customers supporting Windows Server 2003.

The problem we found was how do you escape path names properly given we were getting some varying results.

Let's say for example we have a file here "D:\WmiTest\Dave's.exe" and we want to get the information using the CIM_DataFile class.


Correct query
You can use single quotes for the query parameter but you must then escape both the backslashes and the single quote.

SELECT * FROM CIM_DataFile WHERE Name='D:\\WmiTest\\Dave\'s.exe'


Correct query
You can use double quotes for the query parameter but you must then escape the backslashes but not the single quote.

SELECT * FROM CIM_DataFile WHERE Name="D:\\WmiTest\\Dave's.exe"


Correct Object Path
The correct object path should use double quotes, escape the backslashes but not escape the single quote.

CIM_DataFile.Name="D:\\WmiTest\\Dave's.exe"

Comments

Popular posts from this blog

Windows Server 2016, 2019, 2022, Windows 10 and Windows 11: Date and time "Some settings are managed by your organization".

TFTPD32 or TFTPD64 reports Bind error 10013 An attempt was made to access a socket in a way forbidden by its access permissions.

Enable function lock for F1-F12 on HP ZBook mobile workstations