如何将包含 <SPACE> 的参数从 C# 传递到 powershell.exe

问题描述 投票:0回答:1

我想在 C# 中启动一个进程,导致 powershell 启动另一个需要类似参数的程序:“M=ab”。我尝试过各种文字字符串格式,但无济于事。 在 PowerShell 中,以下工作正常:

Start-Process -FilePath 'C:\MY.exe' -ArgumentList 'A','"M=a b"'

在 C# 中,以下内容无法正常工作(My.exe 抛出:“M=a”未找到。)

string arg = @"Start-Process -FilePath 'C:\MY.exe' -ArgumentList 'A','""M=a b""'";
psTry("powershell.exe",arg)

static void psTry(string file,string arg)
{
    Process process = new Process();
    process.StartInfo.FileName = file;
    process.StartInfo.Arguments = arg;
    process.Start();
}

我在 PowerShell 和 C# 中尝试了 和 " 的各种组合。我尝试了诸如 arg = @"...".ToString() + @"'""M=a b""'".ToString()

c# powershell string-literals
1个回答
0
投票

@"... '""M=a b""'"
替换为
@"... '\""M=a b\""'"

也就是说,在 C# 逐字字符串中,使用

\""
生成
\"
,这是为了将
"
通过 verbatim 传递到最终执行的 PowerShell 命令所必需的。

powershell.exe
,Windows PowerShell CLI,[1] 需要
"
字符。保留作为命令的一部分,转义为
\"
- 未转义
"
字符。假定具有语法函数仅在命令行上,因此在参数(的串联)被评估为 PowerShell 代码之前被删除


[1] 这同样适用于

pwsh.exe
,PowerShell(核心)CLI;后者可选择接受
""
.

© www.soinside.com 2019 - 2024. All rights reserved.