首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法从App #/.NET Core内部执行PowerShell脚本

无法从App #/.NET Core内部执行PowerShell脚本
EN

Stack Overflow用户
提问于 2022-03-12 14:09:54
回答 1查看 272关注 0票数 3

我不太清楚为什么,但是如果我从我的解决方案之外的本地文件夹执行一个脚本,一切都很好。当我在我的项目中调用文件时,我会得到以下错误:

代码语言:javascript
运行
复制
System.Management.Automation.PSSecurityException: 'AuthorizationManager check failed.'

Inner Exception
FileNotFoundException: C:\path\to\myproject\Modules\PSDiagnostics\PSDiagnostics.psm1

这是我试图运行的代码:

代码语言:javascript
运行
复制
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:\脚本中,也不应该存在于我的应用程序目录中。

EN

回答 1

Stack Overflow用户

发布于 2022-10-06 08:32:44

如果您正在构建一个独立的应用程序,那么这是一个已知的问题。模块未正确部署到发布文件夹中。请参阅https://github.com/PowerShell/PowerShell/issues/15274

我修正了这个问题,增加了一个构建步骤,将模块复制到正确的位置。有一个更复杂的解决方案在提到的Github问题,我把它简化为一个更简单的构建任务,因为我只是针对Windows。

代码语言:javascript
运行
复制
<!--
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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71450320

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档