Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ps1 cannot be loaded because running scripts is disabled on this system

Tags:

c#

powershell

I try to run powershell script from c#.

First i set the ExecutionPolicy to Unrestricted and the script is running now from PowerShell ISE.

Now this is c# my code:

class Program {     private static PowerShell ps;     static void Main(string[] args)     {         ps = PowerShell.Create();         string ps1File = Path.Combine(Environment.CurrentDirectory, "script.ps1");         ExecuteScript(ps1File);         Console.ReadLine();     }      static void ExecuteScript(string script)     {         try         {             ps.AddScript(script);             Collection<PSObject> results = ps.Invoke();             Console.WriteLine("Output:");             foreach (var psObject in results)             {                 Console.WriteLine(psObject);             }             Console.WriteLine("Non-terminating errors:");             foreach (ErrorRecord err in ps.Streams.Error)             {                 Console.WriteLine(err.ToString());             }         }         catch (RuntimeException ex)         {             Console.WriteLine("Terminating error:");             Console.WriteLine(ex.Message);         }     } } 

And the output is:

ps1 cannot be loaded because running scripts is disabled on this system. For more informationm see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.

like image 497
user979033 Avatar asked Dec 13 '16 09:12

user979033


People also ask

How do you fix error ps1 Cannot be loaded because running scripts is disabled?

ps1 cannot be loaded because running scripts is disabled on this system" occurs when the execution policy does not allow running the specific script on Windows. Use the Set-ExecutionPolicy -ExecutionPolicy RemoteSigned command to solve the error.


1 Answers

This could be due to the current user having an undefined ExecutionPolicy.

You could try the following:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted 
like image 93
Tom Avatar answered Sep 26 '22 03:09

Tom