I'm building a C# application that has to run some powershell scripts.
While the application works well on all my colleagues computers, I have issue having it to work properly on a Windows Server 2012 virtual machine.
Whenever I run a script through the application I'm getting the following error message:
Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. To change the execution policy for the default (LocalMachine) scope, start Windows PowerShell with the "Run as administrator" option. To change the execution policy for the current user, run "Set-ExecutionPolicy -Scope CurrentUser".
I precise that I went through a LOT of topics and tried many things that did not solve my problem I tried:
set-executionpolicy unrestricted
set-executionpolicy unrestricted -Scope -CurrentUser
And of course I ran these commands on both x64 and x86 powershell instances (running the powershell application as administrator)
Now the strange part is that I have no trouble running the script through the powershell window directly, the error only occurs when running the script through the C# application.
Here's the code involved:
public static List<string> RunPowerShellScript(Sequence sq, Script script)
{
try
{
script.Results = new List<Result>();
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
RunspaceInvoke runspaceInvoker = new RunspaceInvoke(runspace);
//runspaceInvoker.Invoke("set-executionpolicy bypass");
runspaceInvoker.Invoke("set-executionpolicy unrestricted");
//Create a pipeline to send variables
Pipeline pipeline = runspace.CreatePipeline();
//Create a command
Command myCommand = new Command(Properties.Settings.Default.Scripts + "\\" + script.ScriptName + ".ps1", false);
foreach (Parameter p in script.Parameters)
{
CommandParameter param = new CommandParameter(p.ParameterName, sq.GetUpdatedParameter(p));
myCommand.Parameters.Add(param);
}
pipeline.Commands.Add(myCommand);
//Return the output from the script
Collection<PSObject> returnObjects = pipeline.Invoke();
runspace.Close();
List<string> output = new List<string>();
foreach (PSObject po in returnObjects)
{
if (po != null)
output.Add(po.ToString());
}
return output;
}
catch(Exception e)
{
return new List<string> { e.Message, "1" };
}
}
powershell –ExecutionPolicy Bypass -File C:\Path\to\Script
. You will want to run this as a shell command (CMD) rather than a powershell command and it will knock the powershell script open. – HarveySystem.Diagnostics.Process.Start("CMD.exe", powershell -ExecutionPolicy Bypass -File C:\Path\to\Script);'
That will open a cmd and run the Powershell script with execution policy bypassed – HarveyGet-ExecutionPolicy -List
in a Powershell window to verify that your domain for the Windows Server is not overriding your policy change with a group policy. If it is, then there really isn't much you can do to change it without asking your domain administrator to change the GP – Harvey