Powershell, Posh-SSH Module: How is reading the stream supposed to work in Posh-SSH?

I'm trying to understand how reading a stream is supposed to work in Posh-SSH so I can put together a "wait-action" function so the script will continue only after the remote command has completed.

The intent of the code shown below, when put together, is to kick off a "yum update" on the remote system (Linux, CentOS 7), then monitor the stream to determine when the remote command has completed, then proceed to the next line of the script. It does work "sometimes", but not consistently.

This code successfully sets up a new SSH Connection and defines a stream:

$hostIP = "Remote_Linux_Server_IP"
$centosCreds = "My_Credential_Object"
$pemFile = "My_Pem_File"
New-SSHSession -ComputerName $hostIP -Port 22 -Credential $centosCreds -KeyFile $pemFile -ConnectionTimeout 120 -OperationTimeout 120 -AcceptKey
$stream = New-SSHShellStream -Index 0

Executing a remote command through the new stream is easy enough:

Invoke-SSHStreamShellCommand -ShellStream $stream -Command "yum update"

Running the following while the Invoke-SSHStreamShellCommand command (yum update) is running returns a snippet of the remote command output as expected:

$stream.Read()

However, once the "yum update" is complete, the stream read returns only a blank value. The information I've been able to find online indicates that the stream read should return the remote system command prompt string, but this does not appear to be the case.

Because the value returned by the read after the command has completed is blank, the "wait-action" loop I'm trying to put together doesn't work consistently:

$promptString = "Remote_System_Command_Prompt_String"
$streamOut = $stream.Read()
while ($streamOut -notlike "*$promptString*") { Start-Sleep -s 1 $streamOut = $stream.Read()
}

I'm not sure what I'm missing here - documentation is limited and I haven't been able to find many other examples of Posh-SSH stream reading that match the behavior I'm seeing.

Any guidance or suggestions are appreciated.

Thanks.

3

1 Answer

This post is super old but was never answered really. I have never seen stream.reaed() return a command prompt. Some variation of this should probably work:

$promptString = "Remote_System_Command_Prompt_String"
$streamOut = $stream.Read()
while (($streamOut).length -ne 0) { Start-Sleep -s 1 $streamOut = $stream.Read()
}

other options would be to use -match and look for the phrase it uses when complete or sleeping longer and then checking the yum log for verification that it updated. Any of these would probably accomplish the task.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like