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

user979033 picture user979033 · Dec 13, 2016 · Viewed 126.3k times · Source

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.

Answer

Tom picture Tom · Mar 5, 2018

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

You could try the following:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted