来自流程的设置执行策略

时间:2015-12-07 18:09:55

标签: c# powershell vsto

我正在为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();
} 

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

3 个答案:

答案 0 :(得分:4)

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

var_dump( file_get_contents(http://input) );

即使没有以管理员身份运行代码,这对我也很有效。我在Windows 10中使用带有Powershell 5的Visual Studio 2015。

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

答案 1 :(得分:0)

您在Windows 7上拥有的powershell版本是什么?如果它不是V.4,你可以在那里得到它:https://support.microsoft.com/en-us/kb/2819745。 然后,如果您使用的不是V.4,请使用不受限制的策略再次尝试。

另外,当其他真正令人兴奋的事情没有发生时,你有错误信息吗?如果是这样,请将其添加到您的问题中,以便我们找到更多关于您的问题的线索。

答案 2 :(得分:0)

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

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。这意味着,如果使用组策略或本地策略(UserPolicy或MachinePolicy)定义了ExecutionPolicy,则不会覆盖ExecutionPolicy。

选中Get-ExecutionPolicy -List,以查看在当前过程的不同范围内定义的ExecutionPolicies列表。

相关问题