Output is truncated in Jenkins job when launching PowerShell script remotely using psexec

I've created a job in Jenkins to launch a small powershell script on a remote machine using psexec. In my build step, I'm using the powershell plugin and launching the below command:

& "$env:SCRIPTROOT\test_psexec.ps1" -Username $env:USERNAME -Password $env:PASSWORD -Server $env:REMOTESERVER

In the test_psexec.ps1 file, I have the code below:

$filePath = "C:\windows\temp\test_script.ps1"
$server = "server01"
$cmd = "powershell -NoLogo -NonInteractive -ExecutionPolicy Bypass -File $filePath"

Write-Host "Launching powershell on remote system using psexec..."
Write-Host "Command: & $PSScriptRoot\tools\psexec -accepteula -nobanner -u $username -p **** -h \\$server $cmd"

$output = & $PSScriptRoot\tools\psexec -accepteula -nobanner -u $username -p $password -h \\$server $cmd
Write-Host "Script Output: "
Write-Host $output

The test_script.ps1 file contains the following script:

Write-Host "Verifying if server is pending reboot..."

try {
  $regKey = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"
  $regItems = Get-ItemProperty -Path $regKey -ErrorAction SilentlyContinue

  if($regItems) {
    Write-Host "Server has a reboot pending. Rebooting server..."
  } else {
    Write-Host "Server does not have a pending reboot."
  }
} catch {
  Write-Host "Failed to verify pending reboot or unable to restart server."
  Write-Host $_.Message
}

The job executes successfully, but for some reason, the output that I display from psexec in Jenkins only returns one line. I executed another test script on the remote machine with a bunch of text, and it seems to be truncating the output at 256 characters. The Jenkins job output looks similar to what is below:

Started by user Test Account
Building in workspace D:\Jenkins\workspace\test_job
[test_job] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\windows\TEMP\jenkins3570507542870234918.ps1'"
Launching powershell on remote system using psexec...
Command: D:\test_job\tools\psexec.exe -accepteula -nobanner -u testdomain\test_acct -p **** -h \\server01 "powershell" -NoLogo -NonInteractive -ExecutionPolicy Bypass -File C:\windows\temp\test_script.ps1
Connecting to server01...
Starting PSEXESVC service on server01...
Connecting with PsExec service on server01...
Starting powershell on server01...
powershell exited on server01 with error code 0.
Script Output: 
Verifying if server is pending reboot...
Execution successful.
Finished: SUCCESS

If I log onto and launch the script on the remote machine in PowerShell, I get the appropriate output. Also, I am not launching psexec in Jenkins directly as there is other logic around this part of the test_psexec.ps1 script which is irrelevant to this issue.

Does anyone know if I am hitting some sort of buffer limit or know of a setting I can configure to avoid this issue?

0
задан 7 July 2017 в 01:31
1 ответ

Причина, по которой это не работает для вас, заключается в том, что ваш второй сценарий использует Write-Host . Выход Write-Host не может быть перенаправлен; поэтому, когда вы выполняете этот скрипт удаленно, вывод теряется.

В вашем случае лучшей альтернативой является Write-Out , который записывает объекты в выходной поток. Это должно работать нормально в данном конкретном случае, но имейте в виду, что функция записи дает неожиданные результаты при использовании в функции, которая должна возвращать другие результаты в выходной поток. (В Powershell возврат значения из функции эквивалентен Write-Out .)

Другой альтернативой является Write-Verbose , которая записывает результаты в подробный поток. Чтобы увидеть эти результаты, вам нужно либо добавить флаг -Verbose к вызову сценария, либо установить $ VerbosePreference = $ true , чтобы установить его для своего сеанса.

Вот хорошая статья, в которой рассказывается о подводных камнях Write-Host : http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful /

1
ответ дан 4 December 2019 в 16:12

Теги

Похожие вопросы