3r1*_*r1c 4 c# powershell powershell-sdk executionpolicy
我尝试结合 stackoverflow 的两个答案(第一和第二)
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();
Run Code Online (Sandbox Code Playgroud)
在我的 powershell 脚本中,我有以下参数:
Param(
[String]$key
)
Run Code Online (Sandbox Code Playgroud)
但是,当我执行此操作时,会出现以下异常:
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.
Run Code Online (Sandbox Code Playgroud)
在不知道您的具体问题是什么的情况下,请注意您的 C# 代码可以大大简化,这也可能会解决您的问题:
无需诉诸反射来设置会话的执行策略。
使用该类的实例PowerShell极大地简化了命令调用。
// 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();
Run Code Online (Sandbox Code Playgroud)
注意:如果在执行 PowerShell 脚本期间发生终止.Invoke()错误,该方法只会引发异常。更典型的非终止错误是通过 报告的。.Streams.Error
| 归档时间: |
|
| 查看次数: |
2579 次 |
| 最近记录: |