Q:

How to lauch dotnet.exe in a new command prompt without closing it before I call CloseMainWindow?

I would like to launch a .NET Core Web app in a batch file and then send a client request to it, then close the Web app.
cd $PSScriptRoot
$DevWebRootPath=$PSScriptRoot+"\MyWebApp\bin\Debug\netcoreapp2.0"
$WebAssembly="MyWebApp.dll"
cd $DevWebRootPath
$processInfo = New-Object System.Diagnostics.ProcessStartInfo("dotnet.exe", $WebAssembly)
$process = [System.Diagnostics.Process]::Start($processInfo)

Invoke-RestMethod http://localhost:5000/api/codegen -Method POST -InFile "$($PSScriptRoot)\MyWebApp\Payload.json" -ContentType "application/json"

$process.CloseMainWindow()
cd $PSScriptRoot

However, the CMD window hosting the .net core process just disappear right after launching, before Invoke-RestMethod or process.CloseMainMaindow() could run. I had tried similar practices with iisexpress.exe and asp.net Web API, it was working well.
How to lauch dotnet.exe in a new command prompt without closing it before I call CloseMainWindow?

A:

I'd avoid manual .NET manipulation where you can and rely on built-in methods (that's the entire point of cmdlets):
$path = "$PSScriptRoot\MyWebApp\bin\Debug\netcoreapp2.0"
$procArgs = @{
    FilePath         = "$path\dotnet.exe"
    ArgumentList     = "$path\MyWebApp.dll"
    WorkingDirectory = $path
    PassThru         = $true
}
$process = Start-Process @procArgs

$restArgs = @{
    Uri         = 'http://localhost:5000/api/codegen'
    Method      = 'Post'
    InFile      = "$PSScriptRoot\MyWebApp\Payload.json"
    ContentType = 'application/json'
}
Invoke-RestMethod @restArgs

$process.CloseMainWindow() # Should be `$process | Stop-Process`

As a default, Start-Process opens the window in a new console unless you use -NoNewWindow.

