I'm not quite sure why, but if I execute a script from a local folder outside my solution things run fine. When I call the file inside my project I get the following error:
System.Management.Automation.PSSecurityException: 'AuthorizationManager check failed.'
Inner Exception
FileNotFoundException: C:\path\to\myproject\Modules\PSDiagnostics\PSDiagnostics.psm1
This is the code I am trying to run:
InitialSessionState _initialSessionState = InitialSessionState.CreateDefault2();
_initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
//var script = Environment.CurrentDirectory + @"\MachineInfo.ps1";
var script = @"C:\scripts\MachineInfo.ps1";
using (var run = RunspaceFactory.CreateRunspace(_initialSessionState))
{
run.Open();
var ps = PowerShell.Create(run);
ps.AddCommand("Import-Module");
ps.AddParameter("SkipEditionCheck");
ps.AddArgument("CIMcmdlets");
ps.Invoke();
var err = run.SessionStateProxy.PSVariable.GetValue("error");
System.Diagnostics.Debug.WriteLine(err);//This will reveal any error loading
ps.AddCommand(script);
ps.AddArgument(Machine);
var result = ps.Invoke();
run.Close();
}
Can anyone help me understand why it only works if I call script
externally (see the commented out line) from the project source? I'm setting MachineInfo.ps1 to Copy Always and Content (I've tried None too) for Build Action.
This is running via PowerShell 7 inside a C# WinUI 3 .NET Core app. PSDiagnostics.psm1 does not exist inside C:\scripts nor should it have to exist inside my app directory.