【问题标题】:Set-Execution Policy from process从流程设置执行策略
【发布时间】:2019-12-18 02:07:20
【问题描述】:

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

这一切都在我的 Windows 10 机器上完美运行,具有机器级不受限制的 PowerShell 执行策略。但是,我无法让它在客户端的 Windows 7 机器上运行。

我认为有两个问题。一个可能是他的 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();
} 

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

【问题讨论】:

  • 你是以管理员身份运行的吗?
  • 是的,这是作为 Office 365 管理员运行的。该代码在我的 Windows 10 PowerShell 5 不受限制的机器上运行良好。我还将 Windows 7 机器升级到 PowerShell 5,它也可以不受限制地运行代码。似乎由于某种原因我的“Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted;”命令在设置为受限的机器上不起作用。我希望该命令甚至可以在设置为受限的机器上运行该进程。 44
  • 我查看了我的代码块,发现与发布它时的情况有所不同。调用已从最后一行中删除。这个标准是删除调用吗?我只是想了解编辑。除了调用之外,似乎大多数编辑只是对明显较差的英语技能的清理。
  • 删除 Invoke 调用可能是一个错误,被错误地批准了。

标签: c# powershell vsto


【解决方案1】:

我刚刚创建了一个新的控制台项目并将其添加到 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。

根据the Powershell 4.0 Set-ExecutionPolicythe Powershell 5.0 Set-ExecutionPolicy,Set-ExecutionPolicy 在 Powershell 4 和 5 中的工作方式相同。

【讨论】:

  • 所以我测试了上面的代码。事实上它确实工作正常。这是我需要感谢的推动力。我改为绕过,我认为问题在于我需要分两步完成。第一步切换到我的绕过,我的第二个调用调用能够成功完成,但如果我试图在一个脚本中调用它,所有其他项目都会失败。感谢您的时间和帮助先生们。
【解决方案2】:

尝试使用反射来做到这一点。

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 中的 ExecutionPolicy 有 5 个级别 (scope)(请参阅about_execution_policies)。这将设置 Process 的 ExecutionPolicy。这意味着如果 ExecutionPolicy 是使用组策略或本地策略(UserPolicy 或 MachinePolicy)定义的,则不会覆盖 ExecutionPolicy。

检查 Get-ExecutionPolicy -List 以查看在当前流程的不同范围内定义的 ExecutionPolicies 列表。

【讨论】:

    猜你喜欢
    • 2022-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2021-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多