C#调用PowerShell脚本传参报错,请求排查问题原因
问题根源
你当前的代码里,AddArgument/AddParameter是给**最后一个添加的命令(Out-String)**传参,而不是传给你的Test.ps1脚本,这才导致了参数不匹配的错误。
修正方案
有两种规范的传参方式:
方式一:用AddCommand调用脚本(推荐)
用AddCommand加载脚本文件,然后直接给这个命令添加参数,这样参数会正确绑定到脚本的FilePrefix参数上:
using (PowerShell ps = PowerShell.Create()) { var scriptfile = @"\\cbc0056\work\Powershell\Scenarios\Test.ps1"; // 设置执行策略 ps.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", "RemoteSigned") .AddParameter("Scope", "Process") .AddParameter("Force"); // 调用脚本文件并传递参数 ps.AddCommand(scriptfile) .AddParameter("FilePrefix", "Test 222") // 此参数直接绑定到Test.ps1的FilePrefix .AddCommand("Out-String"); // 处理脚本输出 Collection<PSObject> results = ps.Invoke(); foreach (PSObject item in results) { _logger.LogInformation("Power Shell returned Values as given below " + "\r\n"+item.BaseObject.ToString()); // 业务逻辑 } }
如果想用 positional 参数(对应脚本里的Position=1),可以把.AddParameter("FilePrefix", "Test 222")换成.AddArgument("Test 222")。
方式二:用AddScript传递带参数的命令字符串
把脚本路径和参数拼接成完整的PowerShell命令字符串传给AddScript,注意处理引号转义:
using (PowerShell ps = PowerShell.Create()) { var scriptfile = @"\\cbc0056\work\Powershell\Scenarios\Test.ps1"; ps.AddCommand("Set-ExecutionPolicy") .AddParameter("ExecutionPolicy", "RemoteSigned") .AddParameter("Scope", "Process") .AddParameter("Force"); // 拼接脚本路径与参数 ps.AddScript($@"""{scriptfile}"" -FilePrefix 'Test 222'") .AddCommand("Out-String"); Collection<PSObject> results = ps.Invoke(); foreach (PSObject item in results) { _logger.LogInformation("Power Shell returned Values as given below " + "\r\n"+item.BaseObject.ToString()); // 业务逻辑 } }
额外说明
脚本里的Write-Host输出默认不会被Invoke()捕获,因为Write-Host是直接输出到控制台而非返回值。如果要捕获这部分内容,需要把脚本里的Write-Host改成Write-Output,或者在C#里订阅ps.Streams.Information事件获取信息。
内容的提问来源于stack exchange,提问作者sha
相关产品推荐
相关产品推荐

