从进程设置执行策略

本文关键字:策略 执行 设置 进程 | 更新日期: 2023-09-27 18:26:10

我正在C#中为Outlook做一个VSTO加载项,它调用PowerShell脚本与Office 365的Exchange Online交互。

它在我的windows 10计算机上运行得很好,具有计算机级别的无限制PowerShell执行策略。但是,我无法让它在客户端的Windows7机器上运行。

我认为有两个问题。一个可能是他的windows 7 PowerShell需要更新才能使用我的代码,另一个是我没有正确设置进程执行策略。这是我为使执行策略设置为不受限制所做的最大努力(绕过会更好吗?)。

using (PowerShell PowerShellInstance = PowerShell.Create())
{
    StringBuilder OSScript = new StringBuilder("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted;");
    OSScript.Append(@"other really exciting stuff");
    PowerShellInstance.AddScript(OSScript.ToString());
    PowerShellInstance.Invoke();
} 

有人能给我指对方向吗?我知道这不起作用,就好像我把机器策略设置为限制一样。其他真正令人兴奋的事情不会发生,但如果我把它设置为不受限制,那么一切都会起作用。

从进程设置执行策略

我刚刚创建了一个新的Console项目,并将其添加到Main:中

using (PowerShell PowerShellInstance = PowerShell.Create())
{
    string script = "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted; Get-ExecutionPolicy"; // the second command to know the ExecutionPolicy level
    PowerShellInstance.AddScript(script);
    var someResult = PowerShellInstance.Invoke();
    someResult.ToList().ForEach(c => Console.WriteLine(c.ToString()));
    Console.ReadLine();
}   

这对我来说非常有效,即使不以管理员身份运行代码。我正在使用带有Powershell 5的Windows 10中的Visual Studio 2015。

根据Powershell 4.0设置执行策略和Powershell 5.0设置执行策略,设置执行策略在Powershell 4和5中的工作方式相同。

尝试使用反射来完成此操作。

using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Reflection;
using Microsoft.PowerShell;
...
InitialSessionState iss = InitialSessionState.CreateDefault();
// Override ExecutionPolicy
PropertyInfo execPolProp = iss.GetType().GetProperty(@"ExecutionPolicy");
if (execPolProp != null && execPolProp.CanWrite)
{
    execPolProp.SetValue(iss, ExecutionPolicy.Bypass, null);
}
Runspace rs = RunspaceFactory.CreateRunspace(iss);
rs.Open();

请注意:PowerShell中有5个级别(scope)的ExecutionPolicy(请参阅about_execution_policies)。这将设置Process的ExecutionPolicy。这意味着,如果该ExecutionPolicy是用组策略或本地策略(UserPolicy或MachinePolicy)定义的,则不会覆盖ExecutionPolicy。

检查Get-ExecutionPolicy -List以查看在当前进程的不同作用域中定义的ExecutionPolicies列表。