Pipe a string of commands over ssh

I’m trying to pipe commands to a host running a different OS via ssh. I need to send the commands as one string. Sending one at a time isn’t an option. I can get this to work using quotes and newlines when I test on the ps cli. For example, sending 3 commands:

Write-Output "Command1`nCommand2s`nCommand3`n" | ssh -tt user@host > out.txt

The out.txt file gets populated with my command output.

$ Command1
$ Command2
$ Command3

When I try the same thing in ps script it doesn’t work:

$cmds="'Command1'`n'Command2'`n'Command3'`n"
Write-Output "commands to be sent:" $cmds
Write-Output $cmds | ssh -tt user@host > out.txt

The output I get shows that the string in $cmds is being formatted correctly as per the manual cli command:

commands to be sent:

"Command1`nCommand2`nCommand3`n"

But on my ssh host it’s being interpreted as:

Error: command ‘Command1`nCommand2`nCommand3`n’ not recognized

Any idea why?

This post was very broken due to the backticks which were being interpreted as code tags by WordPress. Please read the guidance I’ve written about this issue.

There also seemed to be some confusion between the use of the single quote (') and backtick (`) characters, which have very different meanings for PowerShell.

I attempted to repair the post to show what I think you intended, based on the several attempts you made to post it (please don’t post multiple times - if your post was caught by the spam filter, give the moderators some time to retrieve it). You should look over the post to make sure it replicates your code the way you meant.

As to your issue, this method isn’t going to work the way you intend on your “different OS”. It would be much easier to help you if you were more specific about the environment you’re working with, but assuming that the “different OS” is *NIX, one major problem is that backtick is not the escape character for *NIX shells. For instance, if you wanted to echo a newline in Bash, you would type \n and not `n. The backtick character has no special meaning in Bash, and would simply be printed as text. The specific escape sequence you need depends entirely on the shell in use (again, it would be easier to help with more specific information).

Furthermore, sending a newline character to a shell is not the same thing as pressing the Enter or Return key on your keyboard, and won’t result in execution of the command preceding it (newline is just a character, like a space).

I think the best way to accomplish your objective would be to write a script on the remote system in that shell’s format (Bash or w/e) and store that script on the target machine. Then, when you need to execute those commands, you open your ssh connection from your local system and then simply execute the script on the remote system.