我不太清楚为什么,但是如果我从我的解决方案之外的本地文件夹执行一个脚本,一切都很好。当我在我的项目中调用文件时,我会得到以下错误:
System.Management.Automation.PSSecurityException: 'AuthorizationManager check failed.'
Inner Exception
FileNotFoundException: C:\path\to\myproject\Modules\PSDiagnostics\PSDiagnostics.psm1
这是我试图运行的代码:
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();
}
有人能帮助我理解为什么只有当我从项目源外部调用script
(请参阅注释行)时,它才能工作吗?我将MachineInfo.ps1设置为“始终复制”和“内容复制”(我也没有尝试过)以进行构建操作。
这是通过PowerShell 7在C# WinUI 3 .NET核心应用程序中运行的。PSDiagnostics.psm1不存在于C:\脚本中,也不应该存在于我的应用程序目录中。
发布于 2022-10-06 08:32:44
如果您正在构建一个独立的应用程序,那么这是一个已知的问题。模块未正确部署到发布文件夹中。请参阅https://github.com/PowerShell/PowerShell/issues/15274
我修正了这个问题,增加了一个构建步骤,将模块复制到正确的位置。有一个更复杂的解决方案在提到的Github问题,我把它简化为一个更简单的构建任务,因为我只是针对Windows。
<!--
Fix PS modules being in wrong place when publishing with a runtime identifier.
-->
<Target Name="PostPublish" AfterTargets="Publish">
<ItemGroup>
<PowerShellModules Include="$(ProjectDir)$(OutputPath)runtimes\win\lib\net6.0\Modules\**\*.*"/>
</ItemGroup>
<Copy SourceFiles="@(PowerShellModules)" DestinationFiles="$(PublishDir)\Modules\%(RecursiveDir)%(Filename)%(Extension)" />
</Target>
https://stackoverflow.com/questions/71450320
复制相似问题