Reputation: 103
I'm doing a VSTO add in for Outlook in C# that calls PowerShell scripts to interact with the Exchange Online of Office 365.
It all works perfectly on my windows 10 machine with a machine level unrestricted PowerShell execution policy. However, I can't get this to run on the client's Windows 7 machine.
I think there are two issues. One that possibly his windows 7 PowerShell needs to be updated to work with my code, and second that I'm not properly setting the process execution policy. Here was my best effort to get the execution policy set to unrestricted (would bypass be better?).
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();
}
Could someone point me the right direction? I know this doesn't work, as if I set the machine policy to restricted the other really exciting stuff doesn't happen, but if I set it to unrestricted then everything works.
Upvotes: 9
Views: 10809
Reputation: 4634
Trying to do this using reflection.
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();
Please note: There are 5 levels (scope
) of ExecutionPolicy in PowerShell (see about_execution_policies). This will set Process
's ExecutionPolicy. This means if that ExecutionPolicy was defined with Group policy or Local policy ( UserPolicy or MachinePolicy ), this will not override ExecutionPolicy.
Check Get-ExecutionPolicy -List
to see list of ExecutionPolicies defined in different scopes for your current process.
Upvotes: 1
Reputation: 32068
I just created a new Console project and added this to 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();
}
This works perfectly for me, even without running the code as administrator. I'm using Visual Studio 2015 in Windows 10 with Powershell 5.
Set-ExecutionPolicy works in the same way in Powershell 4 and 5, according to the Powershell 4.0 Set-ExecutionPolicy and the Powershell 5.0 Set-ExecutionPolicy.
Upvotes: 9