“Start-Process -NoNewWindow” within a Start-Job?

2019-06-17 01:26发布

问题:

I'm having issues using Start-Process within a Start-Job, specifically when using -NoNewWindow. For example, this test code:

Start-Job -scriptblock {
    Start-Process cmd -NoNewWindow -Wait -ArgumentList '/c', 'echo' | out-null
    Start-Process cmd # We'll never get here
}

get-job | wait-job | receive-job
get-job | remove-job

Returns the following error, that apparently google hasnt heard of:

Receive-Job : There is an error processing data from the background process. Error reported: Cannot process an element with node type "Text". Only Element and EndElement node types are supported.

If I remove the -NoNewWindow everything works just fine. Am I doing something silly, or is there no way to start jobs containing Start-Process -NoNewWindow? Any good alternatives?

回答1:

A little late, but for people still having issues with this specific error message, one fix for this example is to use -WindowStyle Hidden instead of -NoNewWindow, I've had -NoNewWindow appear to get ignored a lot of the time and cause it's own problems.

But for this specific error that seems to come from using Start-Process with various executables, I have found the solution that seems to work consistently is by redirecting the output, as it is the output that comes back appears to cause the problem. Unfortunately though that does result in writing to a temporary file and cleaning it up.

As an example;

Start-Job -ScriptBlock {
    # Create a temporary file to redirect output to.
    [String]$temporaryFilePath = [System.IO.Path]::GetTempFileName()

    [HashTable]$parmeters = @{
        'FilePath' = 'cmd';
        'Wait' = $true;
        'ArgumentList' = @('/c', 'echo');
        'RedirectStandardOutput' = $temporaryFilePath;
    }
    Start-Process @parmeters | Out-Null

    Start-Process -FilePath cmd

    # Clean up the temporary file.
    Remove-Item -Path $temporaryFilePath
}

Get-Job | Wait-Job | Receive-Job
Get-Job | Remove-Job

Hopefully this helps.