0

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.

1 Answer 1

0

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();
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.