C# 将引号传递到c代码中的powershell脚本不会';行不通
我已经编写了c#代码,它使用参数执行powershell脚本。它工作得很好。但是,当我尝试向该方法传递一个带有引号的参数时,例如全名,它似乎无法识别引号,只能识别第一个标记 下面是我如何创建脚本参数的。您可以看到,fullName变量应该在结果scriptArguments中用引号括起来C# 将引号传递到c代码中的powershell脚本不会';行不通,c#,C#,我已经编写了c#代码,它使用参数执行powershell脚本。它工作得很好。但是,当我尝试向该方法传递一个带有引号的参数时,例如全名,它似乎无法识别引号,只能识别第一个标记 下面是我如何创建脚本参数的。您可以看到,fullName变量应该在结果scriptArguments中用引号括起来 string scriptArguments = $@"-Phone {phoneNumber} -Name ""{fullName}""";
string scriptArguments = $@"-Phone {phoneNumber} -Name ""{fullName}""";
var result = ExecutePowerShellScript(null, "MyScript.ps1", scriptArguments);
当我在调试中查看scriptArguments变量时,它确实正确显示
-Phone 321-555-1111 -Name "John Smith"
我甚至可以手动运行shell脚本,并在命令行中复制/粘贴scriptArguments的结果,ps1运行得非常好!比如
.\MyScript.ps1 -Phone 321-555-1111 -Name "John Smith"
但是,当我允许ExecutePowerShellScript方法运行脚本时,它只识别fullName的第一个标记John。下面是ExecutePowerShelScript方法,部分
public PowerShellExecutionResult ExecuteScript(string scriptToExecute, string scriptArgument)
{
scriptToExecute = ConfigurationManager.AppSettings[“myscriptpath"] + scriptToExecute;
try
{
using (var process = new Process
{
StartInfo =
{
UseShellExecute = false,
RedirectStandardOutput = true,
FileName = ConfigurationManager.AppSettings["powershell-exe-“path],
Arguments = $"{scriptToExecute} {scriptArgument}"
}
})
{
process.Start();
logCapture.Add(process.StandardOutput.ReadToEnd());
process.WaitForExit();
}
基本上,shell脚本告诉我“John”已经存在于服务数据库中。如果有的话,它应该说“约翰·史密斯”,而不仅仅是字符串的第一个标记。同样,如果我手动运行它,它就像一个符咒。这表明问题不在shell脚本本身
知道发生了什么吗?我相信我做的每件事都是正确的。尝试用三个引号转义全名:
-Phone 321-555-1111 -Name "John Smith"
string scriptArguments = $"-Phone {phoneNumber} -Name \"\"\"{fullName}\"\"\"";
在最后一个参数中包含字符需要三个转义引号。请参阅。这可能有帮助:使用API而不是直接调用
powershell.exe
:-)