我需要在初始会话状态或以某种方式在执行脚本之前将 ExecutionPolicy 配置为“RemoteSigned”。我不想执行脚本来设置策略。这会改变我不想要的客户端机器上的策略。
在 Powershell 5.0 参考程序集中可以轻松完成,
var iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = ExecutionPolicy.RemoteSigned
但是如何在保留 Powershell 4.0 作为引用程序集的同时实现相同的目标。
执行脚本的 C# 代码
var iss = InitialSessionState.CreateDefault();
iss.ExecutionPolicy = ExecutionPolicy.RemoteSigned; --> this is OK for Powershell ReferenceAssemblies 5.0 but not 4.0
iss.ImportPSModule(new[] { typeof(Parameter).Assembly.Location });
using (var powerShell = PowerShell.Create(iss))
{
var psScript = _inlineScript ?? File.ReadAllText(_path);
powerShell.AddScript(psScript);
}