如何从 PowerShell SDK 调用使用 `Start-ThreadJob` 的代码?

问题描述 投票:0回答:1

我有一个使用 PowerShell SDK 在后台执行 PowerShell 代码的应用程序。

但是,该代码依赖于

Start-Job
,当我在应用程序中运行 PowerShell 脚本时,它会引发异常:

_powerShellInstance.AddScript("DoSomethingWithStartJob").Invoke();

在“C:\Users en\Projects\Foo\Foo (Package) in\x64\Debug\AppX\Foo”中找不到 pwsh 可执行文件 untimes\win\lib et8.0\pwsh.exe”。 请注意,在 PowerShell 托管在其他应用程序中的情况下,设计不支持“Start-Job”。相反,在这种情况下建议使用“ThreadJob”模块。

我想像错误所说的那样移植以使用

Start-ThreadJob
,但我不知道如何!如何让我的 C# 应用程序ThreadJob 模块安装到我的 PowerShell SDK 安装中?

.net powershell msbuild csproj
1个回答
0
投票

这应该适用于 PSGallery 中可用的任何 PS 模块。特别支持

ThreadJob

  1. 在我们的 feed 中添加了
    ThreadJob
    的 PSGallery nuget 包
  2. 创建了一个自定义构建步骤来手动将
    ThreadJob
    模块内容复制到我们的输出目录。

将 ThreadJob 添加到 feed

在您的

nuget.config
示例nuget.config)中:

  <packageSources>
    <clear />
    <!-- ... -->
    <add key="PSGallery" value="https://www.powershellgallery.com/api/v2/" />
  </packageSources>

在您的

csproj
中(示例 csproj;在我们的示例中,我们正在部署 WinUI 项目,因此我们编辑了包
wapproj
):

<ItemGroup>
  <!-- ... -->
  <PackageReference Include="ThreadJob" Version="2.0.3">
    <!-- Necessary for the next step: -->
    <GeneratePathProperty>True</GeneratePathProperty>
  </PackageReference>
</ItemGroup>

这会将包添加到您的项目中。

在我们的例子中,我们在 ADO 中有一个自定义 NuGet 提要,因此我们只需将

ThreadJob
添加到其缓存中。

创建自定义构建步骤

在引用

csproj
包的同一个
wapproj
/
ThreadJob
中:

  <Target Name="CopyThreadJob" AfterTargets="AfterBuild">
    <Message Text="ThreadJob module files: @(ThreadJobFiles)" Importance="high"></Message>
    <Message Text="Deploying ThreadJob module to: $(OutDir)AppX\Foo\runtimes\win\lib\net8.0\Modules\Microsoft.PowerShell.ThreadJob\" Importance="high"></Message>
      <!-- If you want other targets, like UNIX, you'll need to copy to those Modules\ directories, too -->
      <!-- Remember, the subdir in Modules needs to exactly match the name of the .psd1 -->
      <Copy SourceFiles="@(ThreadJobFiles)" DestinationFolder="$(OutDir)\AppX\Foo\runtimes\win\lib\net8.0\Modules\Microsoft.PowerShell.ThreadJob\" SkipUnchangedFiles="true" />
  </Target>

现在您的代码可以调用

Start-ThredJob

_powerShellInstance.AddScript("Start-ThreadJob").Invoke();
© www.soinside.com 2019 - 2024. All rights reserved.