如何将字符串包含在另一个字符串中

How to include string inside another string

我正在尝试 运行 这个命令使用 Power shell:

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

手动 运行 时,它工作正常,但是当我通过代码 运行 时,我收到此错误:

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

这是我的代码:

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;
}

如果你 运行 在 Powershell 中这样做:

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

你也会得到一个错误:

Get-WmiObject : Invalid query "select * from Win32_PnPSignedDriver where DeviceName = \'Microsoft Bluetooth LE Enumerat
or\'"
At line:1 char:1
+ Get-WmiObject Win32_PnPSignedDriver -filter "DeviceName = \'Microsoft ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ManagementException
    + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

不知道你为什么要把\放在单引号前?

但也许您应该使用 System.Management.Automation.Powershell,这似乎更适合这项任务?

如果我没理解错的话,你只是想将文字命令传递给PS。如果是这样,您可以删除 interpolation 和单引号的转义:

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

编辑。 由于您将命令作为参数传递给 powershell.exe,因此您必须转义内部引号。 我同意 Luuk 的观点,你也可以在 SO 上使用 MS's abstractions for this problem. There are some good examples of that 方法。