Run Shell/Linux Commands Remotely After SSH in Windows PowerShell 7 Script

powershellsshwindows

I'm running in to noise trying to find the simplest, most straightforward way to run commands on Linux server after SSH in a .ps1 PowerShell script, running PowerShell 7 on Windows 10.

I have a process that uploads a zip file via SCP/PuTTY, and when completed, my script SSHs in to the server, and from there I need to run a couple Linux commands to unzip the file and run a Docker build/compose.

# param1: destination server ip
$ip=$args[0]
# param2: path on the server
$path=$args[1]
# param3: username
$un=$args[2]
# param4: password # TODO: figure out how to hide
$pw=$args[3]
# source path

if (!$pw) { throw "Password can't be null." }

$src = "../"
# construct archival name
$DateTime = (Get-Date -Format "yyyyMMddHHmmss")
$zip = "..\deploy_archive\deploy-$DateTime.zip"
# Create archive
mkdir -Force ..\deploy_archive
# exclusion rules. 
$files = Get-ChildItem -Path $src -Exclude @("node_modules", "deploy_archive")
# Compress
Compress-Archive -Path $files -DestinationPath $zip -CompressionLevel Fastest
# Report status
Write-Output "`nZipped archive: $($zip)"
# PuTTY SCP file transfer command
$Cmd = ("pscp -l {0} -pw {1} -batch {2} {3}:{4}" -f $un,$pw,$zip,$ip,$path)
Write-Output "cmd: $Cmd"
Invoke-Expression "& $( $Cmd )"
# Report success
Write-Output ("`nUploaded to  {0}:{1}" -f $ip,$path)
# Connect via SSH
ssh ("{0}@{1}" -f $un,$ip)

# ...NOW DO STUFF ON THE REMOTE SERVER
# ...like unzip and run Docker build

I am able to add an oldschool ssh command like:

ssh username@some.ip.add.ress

Then it asks me for my password and connects successfully, but scripts I add after that don't execute until after I exit the SSH session.

If I use:

# SSH-Sessions -ComputerName $ip -Username $un -Password $pw

I get:

> [some.ip.add.ress] The background process reported an error with the
> following message: The SSH client session has ended with error
> message: subsystem request failed on channel 0.

uname -a on the server gives me:

Linux azrahznval0002 3.10.0-1160.15.2.el7.x86_64 #1 SMP Thu Jan 21 16:15:07 EST 2021 x86_64 x86_64 x86_64 GNU/Linux

Best Answer

I found a solution and part of the answer over on StackOverflow where a related question was asked. I wasn't expecting to find this there... But you can run commands inline with the ssh command, which is intuitive, and obvious considering how you'd want to do something like this in most cases.

How am I the first person to post a solution here, lol? Everyone should know this.

Still would like to know why my SSH-Sessions command doesn't work, but that might be something on the server...