含空格文件名导致C#调用PowerShell脚本失败问题求助
解决思路
- 修复参数拼接语法错误:原代码中
psi.Arguments末尾多了一个多余的双引号,这会直接导致PowerShell解析参数时出现异常,尤其是包含空格的参数会被错误拆分。 - 规范PowerShell调用方式:调用脚本时需明确使用
-File参数指定脚本路径,PowerShell会基于这个参数正确解析后续传入的所有参数,包括带空格的内容。 - 优先使用可靠的参数传递方式:若项目基于.NET Core/.NET 5及以上版本,推荐用
ProcessStartInfo.ArgumentList传递参数,无需手动处理引号,框架会自动处理空格和特殊字符的转义。
修正后的参数拼接写法
string MyBatchFile = @"C:\Test\test.ps1"; string Arg2 = "test7 Test8.SQL"; string Arg1 = "-ReplaceValue"; ProcessStartInfo psi = new ProcessStartInfo(); // 明确指定-File参数,正确包裹每个参数并移除末尾多余引号 psi.Arguments = $"-File \"{MyBatchFile}\" \"{Arg1}\" \"{Arg2}\""; psi.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"; Process.Start(psi);
使用ArgumentList的更优写法(.NET Core/.NET 5+)
string MyBatchFile = @"C:\Test\test.ps1"; string Arg2 = "test7 Test8.SQL"; string Arg1 = "-ReplaceValue"; ProcessStartInfo psi = new ProcessStartInfo(); psi.FileName = @"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"; // 通过ArgumentList逐个添加参数,自动处理空格和引号转义 psi.ArgumentList.Add("-File"); psi.ArgumentList.Add(MyBatchFile); psi.ArgumentList.Add(Arg1); psi.ArgumentList.Add(Arg2); Process.Start(psi);
补充说明
使用-File参数时,PowerShell会严格按照传入的参数边界处理内容,带空格的参数只要被正确包裹(或通过ArgumentList传递),就能被完整识别为单个参数,不会被空格拆分。
内容的提问来源于stack exchange,提问作者ashis deb
相关产品推荐
相关产品推荐

