Search code examples
c#wmiwmi-querywql

How can I escape a right-curly brace ( } ) in a directory name of a WMI Win32_Directory query?


I'm trying to execute a WMI query that lists all the subdirectories in a directory on a different network-attached computer (server), but it's failing with a System.Management.ManagementException "Invalid query" exception.

I am practically certain that this issue is due to the directory name containing left- and/or right-curly braces ({, }).

UPDATE: I've determined that the issue is not the left-curly brace, but the right-curly brace.

I've tried various things to escape these characters, but nothing seems to work.

Below is a contrived example that fails with "Invalid query" every time.

using System;
using System.Management;

public static class Program
{
    public static void Main()
    {
        const string username = @"Domain\User";
        const string password = @"Password";
        const string server = @"Server";

        const string query = @"Associators of {"
                             + @"Win32_Directory.Name='"
                             + @"c:\program files (x86)\a_test}"
                             + @"'} "
                             + @"Where AssocClass = Win32_Subdirectory ResultRole = PartComponent";

        var options = new ConnectionOptions { Username = username, Password = password };
        var wmiScope = new ManagementScope(@"\\" + server + @"\root\cimv2", options);
        var wmiQuery = new ObjectQuery(query);
        var searcher = new ManagementObjectSearcher(wmiScope, wmiQuery);
        var searchResults = searcher.Get();

        foreach (var searchResult in searchResults)
        {
            var subPath = searchResult.GetPropertyValue("Name").ToString();
            var system = Convert.ToBoolean(searchResult.GetPropertyValue("System"));
            Console.WriteLine($"subPath = {subPath}; system = {system}");
        }
    }
}

For what it's worth, the code is running on a Windows 10 machine querying a Windows 2008 R2 SP1 server (yes, it's scheduled for demolition).

Thanks!


Solution

  • This appears to be a quirk of the Associators of parsing. To fix this, use the double quote syntax for strings rather than the single quote syntax (taking care to escape backslashes, since this is required for the double quote approach):

    const string query = @"Associators of {"
                         + @"Win32_Directory.Name="""
                         + @"c:\\program files (x86)\\a_test}"
                         + @"""} "
                         + @"Where AssocClass = Win32_Subdirectory ResultRole = PartComponent";