我正在尝试使用 C#
执行 PowerShell 脚本
我的脚本需要参数才能运行,否则会抛出错误。
这是我的脚本的精简版本
param ($url)
if ($url -eq $null) {
throw "No Url was provided"
}
write-host "$url was the provided value"
现在,使用C#
我尝试执行如下脚本
try {
var defaultSessionState = InitialSessionState.CreateDefault();
defaultSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
using PowerShell ps = PowerShell.Create(defaultSessionState);
ps.AddScript(@"d:\test.ps1");
ps.AddParameter("url", "http://example.com/test/");
ps.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "stop");
}
catch (Exception e) {
}
但我不断收到未提供 URL
错误。如何正确地将参数传递给我的脚本,以及如何访问它?
最佳答案
AddScript()
用于执行原始代码 - D:\test.ps1
碰巧是有效代码,但它的意思更丰富用于将完整的独立脚本作为字符串放入。
您需要将脚本文件引用添加为命令,此时我们可以应用参数 - 为此,请改用 AddCommand()
:
using (PowerShell ps = PowerShell.Create(defaultSessionState))
{
ps.AddCommand("d:\test.ps1");
ps.AddParameter("url", "http://example.com/test/");
ps.AddParameter("ErrorAction", "Stop");
// or
ps.Runspace.SessionStateProxy.SetVariable("ErrorActionPreference", "stop");
}
关于c# - 如何使用 C# 将参数传递给 PowerShell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61880309/