我尝试结合 stackoverflow 中的两个答案(first https://stackoverflow.com/questions/527513/execute-powershell-script-from-c-sharp-with-commandline-arguments & second https://stackoverflow.com/questions/34140309/set-execution-policy-from-process)
InitialSessionState iss = InitialSessionState.CreateDefault();
// Override ExecutionPolicy
PropertyInfo execPolProp = iss.GetType().GetProperty(@"ExecutionPolicy");
if (execPolProp != null && execPolProp.CanWrite)
{
execPolProp.SetValue(iss, ExecutionPolicy.Bypass, null);
}
Runspace runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
在我的 powershell 脚本中,我有以下参数:
Param(
[String]$key
)
但是,当我执行此操作时,会出现以下异常:
System.Management.Automation.CmdletInvocationException: Cannot validate argument on parameter 'Session'.
The argument is null or empty.
Provide an argument that is not null or empty, and then try the command again.
在不知道您的具体问题是什么的情况下,请注意您的 C# 代码可以大大简化,这也可能会解决您的问题:
// Create an initial default session state.
var iss = InitialSessionState.CreateDefault2();
// Set its script-file execution policy (for the current session only).
iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Bypass;
// Create a PowerShell instance with a runspace based on the
// initial session state.
PowerShell ps = PowerShell.Create(iss);
// Add the command (script-file call) and its parameters, then invoke.
var results =
ps
.AddCommand(scriptfile)
.AddParameter("key", "value")
.Invoke();
注:.Invoke()
方法仅在以下情况下抛出异常终止执行 PowerShell 脚本期间发生错误。比较典型的是非终止的错误是通过报告的.Streams.Error
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)