如何让 PowerShell 执行脚本中的所有行? (而不在 dotnet 上休息?)

How to get PowerShell to execute all lines in the script? (and not take a rest on dotnet?)

我有一个 PowerShell 版本 5.1.19041.610 脚本,大致执行以下操作

Do Command 1

Do Command 2

dotnet run "..\MyApiProject\API.csproj" --no-build

Do Command 4

它工作正常,直到 dotnet run 劫持会话并输出:

Now listening on: http://localhost:5000
Now listening on: https://localhost:5001
Application started. Press Ctrl+C to shut down.

脚本到此为止。我需要它来执行命令 4。如何让 PowerShell 启动 dotnet 并继续执行下一个命令?

您有两个选项可以防止 同步 dotnet run ... 命令阻止您的脚本。

  • new window 中异步启动 dotnet run ... 命令(仅适用于 Windows),使用 Start-Process
Start-Process dotnet 'run "..\MyApiProject\API.csproj" --no-build'
  • 运行 dotnet run ... 命令在 后台作业 中不可见,使用 Start-Job:[1]
Start-Job { $using:PWD | Set-Location; dotnet run ..\MyApiProject\API.csproj --no-build }
  • 请注意 PowerShell (Core) 7+ now offers a more convenient way to create background jobs, similar to POSIX-compatible shells, via &, the background operator
    • dotnet run ..\MyApiProject\API.csproj --no-build &

    • 此外,更轻量级的选择是使用 thread 作业而不是(基于子进程的)后台作业(ThreadJob 提供 Start-ThreadJob cmdlet 的模块随 PowerShell (Core) 7+ 一起提供,但也可以安装在 Windows PowerShell)

      • Start-ThreadJob { dotnet run ..\MyApiProject\API.csproj --no-build }

[1] 有关如何管理 作业的信息,请参阅概念性 about_Jobs 主题。请注意,在 Windows PowerShell 中需要使用 $using:PWD | Set-Location 以确保后台作业使用与调用者相同的当前位置;在 PowerShell (Core) 7+ 中,这不再是必需的,因为调用者的位置是自动继承的。