Script Execution Policy Error when running PS Command in C# Application from Visual Studio 2019

425 Views Asked by At

This issue has been driving me nuts for a while and I can't figure it out.

I have the following C# code:

class Program
{
    static void Main()
    {
        PowerShell ps = PowerShell.Create();
        ps.AddCommand("Get-StartApps");
        foreach (PSObject result in ps.Invoke())
        {
            Console.WriteLine(
                "{0,-20} {1}",
                result.Members["Name"].Value,
                result.Members["AppID"].Value);
        }
    }
}

This is meant to simply run Get-StartApps which returns a PSObject with Name and AppID (https://learn.microsoft.com/en-us/powershell/module/startlayout/get-startapps?view=windowsserver2019-ps). Then print the output in 2 columns.

However I get the following error when trying to run in Visual Studio:

System.Management.Automation.CommandNotFoundException: 'The 'Get-StartApps' command was found in the module 'StartLayout', but the module could not be loaded. For more information, run 'Import-Module StartLayout'.'

UnauthorizedAccessException: File C:\Windows\system32\WindowsPowerShell\v1.0\Modules\StartLayout\GetStartApps.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.

So it does find the right module, meaning I don't have to manually load it in the code. But it cannot load it for some reason.

I have completely enabled Scripts via GP, on both 64bit and 32bit powershell.This is how it looks:

get-executionpolicy -list

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy    Unrestricted
   UserPolicy    Unrestricted
      Process    Unrestricted
  CurrentUser    Unrestricted
 LocalMachine    Unrestricted

Any thoughts? The same code works for Powershell commands like Get-Process.

0

There are 0 best solutions below