8

我在 Start-Job 中使用 Start-Process 时遇到问题,特别是在使用-NoNewWindow. 例如,这个测试代码:

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

返回以下错误,显然谷歌没有听说过:

Receive-Job : 后台进程处理数据时出错。报告错误:无法处理节点类型为“文本”的元素。仅支持 Element 和 EndElement 节点类型。

如果我删除-NoNewWindow一切正常。我是在做一些愚蠢的事情,还是没有办法开始工作Start-Process -NoNewWindow?有什么好的选择吗?

4

1 回答 1

3

有点晚了,但是对于仍然遇到此特定错误消息的问题的人,此示例的一个修复方法是使用-WindowStyle Hidden而不是-NoNewWindow,我-NoNewWindow似乎很多时候都被忽略并导致它自己的问题。

但是对于这个似乎来自使用Start-Process各种可执行文件的特定错误,我发现似乎始终有效的解决方案是重定向输出,因为返回的输出似乎会导致问题。不幸的是,这确实会导致写入临时文件并清理它。

举个例子;

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

希望这会有所帮助。

于 2017-10-20T23:41:42.367 回答