I have a .NetCore application running in Windows 10 that is attempting to run some scripts with PowerShell.
I'm using the following Automation Library
System.Management.Automation, Version=7.3.3.0
I have the ExecutionPolicy set for LocalMachine set to Unrestricted by running the following command in the Powershell 7 app:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted -scope LocalMachine
I check the ExecutionPolicy settings via:
Get-ExecutionPolicy -List
I see the following output:
Scope ExecutionPolicy
----- ---------------
MachinePolicy Undefined
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Unrestricted
In my .NetCore application I run the following code snippet:
var psInstance = PowerShell.Create();
psInstance.AddScript("Get-ExecutionPolicy -List");
var output = psInstance.Invoke();
If I examine the output, I see the following:
[0] {@{Scope=MachinePolicy; ExecutionPolicy=Undefined}} System.Management.Automation.PSObject
[1] {@{Scope=UserPolicy; ExecutionPolicy=Undefined}} System.Management.Automation.PSObject
[2] {@{Scope=Process; ExecutionPolicy=Undefined}} System.Management.Automation.PSObject
[3] {@{Scope=CurrentUser; ExecutionPolicy=Undefined}} System.Management.Automation.PSObject
[4] {@{Scope=LocalMachine; ExecutionPolicy=Undefined}} System.Management.Automation.PSObject
It seems like the execution policies within my application are not in synch with those I set directly through Powershell.
Why don't the two sets of ExecutionPolicies match up?
Further more, if I attempt to run the following:
var psInstance = PowerShell.Create();
psInstance.AddScript("Get-WindowsCapability -Online -Name ""Language.TextToSpeech~~~fr-FR~0.0.1.0"" | Select-Object -ExpandProperty State";);
var output = psInstance.Invoke();
I get the following error:
The 'Get-WindowsCapability' command was found in the module 'Dism', but the module could not be loaded due to the following error: [File C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Dism\Dism.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.] For more information, run 'Import-Module Dism'.
If I run:
var script = "Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope Process -Force; Get-WindowsCapability -Online -Name ""Language.TextToSpeech~~~fr-FR~0.0.1.0"" | Select-Object -ExpandProperty State";
psInstance.AddScript(script);
var output = psInstance.Invoke();
The command works as expected.
We don't want to have to set the ExecutionPolicy each time we run a script. We want to leverage the execution polices on the local machine. Why I can't I get this to work as expected? Is there another way I should be setting ExecutionPolicy at the machine level?