簡體   English   中英

無法從 App Directory C#/.net Core 中執行 PowerShell 腳本

[英]Unable to execute PowerShell script from inside App Directory C#/.net Core

我不太清楚為什么,但是如果我從我的解決方案之外的本地文件夾執行腳本,一切都會正常運行。 當我在我的項目中調用文件時,出現以下錯誤:

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 設置為 Copy Always 和 Content(我也嘗試過 None)用於構建操作。

這是通過 PowerShell 7 在 C# WinUI 3 .NET 核心應用程序中運行的。 PSDiagnostics.psm1 不存在於 C:\scripts 中,也不應該存在於我的應用程序目錄中。

如果您正在構建一個獨立的應用程序,那么這是一個已知問題。 模塊未正確部署到發布文件夾中。 參見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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM