Search code examples
c#powershellwmic

How to include string inside another string


I'm trying to run this command using Power shell:

Get-WmiObject Win32_PnPSignedDriver -filter "DeviceName = 'Microsoft Bluetooth LE Enumerator'" | select -ExpandProperty driverversion

When running it manually, it works fine, but when I run it via the code, I'm receiving this error:

Get-WmiObject : A positional parameter cannot be found that accepts argument 'Microsoft Bluetooth LE Enumerator'.
At line:1 char:1
+ Get-WmiObject Win32_PnPSignedDriver -filter DeviceName = 'Microsoft B ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Get-WmiObject], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Here is my code:

public static string PlatformModelCommand => $ "Get-WmiObject Win32_PnPSignedDriver -filter \"DeviceName = \'Microsoft Bluetooth LE Enumerator\'\" | select -ExpandProperty driverversion";


string projectName = RunCommandUtil.RunPsProcess(PlatformModelCommand);

public static string RunPsProcess(string arguments)
        {
            return RunProcess("powershell.exe", arguments);
        }

public static string RunProcess(string fileName, string arguments) {
  Process process = new Process();
  process.StartInfo.FileName = fileName;
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.Arguments = arguments;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.RedirectStandardError = true;
  process.Start();
  var output = process.StandardOutput.ReadToEnd();
  output += process.StandardError.ReadToEnd();
  process.WaitForExit();
  return output;
}

Solution

  • If I understood correctly, you just want to pass the literal command to PS. If that's so you could drop the interpolation and the single quotes' escaping:

    public static string PlatformModelCommand => @"""Get-WmiObject Win32_PnPSignedDriver -filter \""DeviceName = 'Microsoft Bluetooth LE Enumerator'\"" | select -ExpandProperty driverversion""";
    

    EDIT. Since you're passing the command as an argument to powershell.exe, you'll have to escape the inner quotes. I agree with Luuk in that you might have a better time using MS's abstractions for this problem. There are some good examples of that approach on SO as well.