【问题标题】:Assign the output message from the console to a variable while running a job在运行作业时将控制台的输出消息分配给变量
【发布时间】:2020-08-19 21:10:20
【问题描述】:

为了包含超时,我在 Powershell 上运行以下作业:

> $job = Start-Job {$PSOut = net use * "<network path>"/persistent:no}
>> $job | Wait-Job -Timeout 30
>> if ($job.State -eq 'Running') {
>>   # Job is still running, cancel it
>>   $job.StopJob()
>> } else {
>>   # Job completed normally, get the result
>> $myArray = $job | Receive-Job

我希望变量 $PSOut 在控制台窗口中携带输出: “驱动器 X:现在已成功映射”

或者: “遇到系统错误 53...”,以防出现错误消息。

但是,$PSOut 总是返回一个空值。

我已经尝试过的: 在 Else 分支中包括以下内容。这样,如果脚本成功执行,我将获得输出,但是当脚本失败时,我还没有找到一种方法来执行此操作。

$PSOut = (Get-job | Receive-job)

【问题讨论】:

    标签: windows powershell mapping


    【解决方案1】:

    我通过在 Receive-Job 命令中包含“2>&1”解决了这个问题。

    "$job = Start-Job {net use * " & in_NetworkPath & "/persistent:no};"
    "$job | Wait-Job -Timeout 60;"
    "If ($job.State -eq 'Running')"
       "{$job.StopJob();"+ _
       "$PSOut = Receive-Job $job 2>&1 | Out-String;"
       "throw "Error encountered: Operation timed out" }"
    "else"
       "{if ($job.Childjobs[0].Error)"
          "{$PSOut = Receive-Job $job 2>&1 | Out-String; Throw $PSOut }"
       "else"
          "{$PSOut = Receive-Job $job | Out-String}}"
    

    这是有效的,因为 Powershell 似乎仅当文本值在信息流中时才允许从 Receive-Job 分配给变量。操作 2>&1 将文本输出从错误流移动到信息流。但是,您必须注意,这会阻止 Powershell 将文本作为错误消息抛出。

    您可以在 [此处][1] 阅读有关 2>&1 操作的更多信息:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-7

    另见:Powershell: get output from Receive-Job

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多