Search code examples
c#powershellazure-powershellexecutionpolicy

Execution Policy Error while executing Powershell script in C# Web API


I am getting below error while executing powershell script. This error is coming when I am trying to import a module -

File C:\Program Files\WindowsPowerShell\Modules\Az.Accounts\2.10.3\Az.Accounts.psm1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.

C# code -

 using (Automation.PowerShell ps = Automation.PowerShell.Create())
            {
                ps.AddScript(script);
                ps.AddParameters(parameters);
                 result = ps.Invoke();
            }

It works fine when I run script directly in powershell console but getting this error while running it via C# web API running in localhost.

Current Execution Policy -

PS C:\Program Files\WindowsPowerShell> Get-ExecutionPolicy Unrestricted PS C:\Program Files\WindowsPowerShell> cd .\Modules
PS C:\Program Files\WindowsPowerShell\Modules> Get-ExecutionPolicy Unrestricted PS C:\Program Files\WindowsPowerShell\Modules> cd Az.Accounts PS C:\Program Files\WindowsPowerShell\Modules\Az.Accounts> Get-ExecutionPolicy Unrestricted PS C:\Program Files\WindowsPowerShell\Modules\Az.Accounts>

Could someone please help on resolving this? Thanks in Advance!!

I have tried setting Execution policy to Unrestricted and ByPass but nothing worked.


Solution

  • Try setting the execution policy within your program:

    using (Automation.PowerShell ps = Automation.PowerShell.Create())
                {
                    ps.AddCommand("Set-ExecutionPolicy").AddArgument("Unrestricted")
        .AddParameter("Scope","CurrentUser");
                    ps.AddScript(script);
                    ps.AddParameters(parameters);
                     result = ps.Invoke();
                }