0

Running tock PowerShell 5.1 on Windows 10 (corporate desktop).

I've been using plink (the putty command-line utility) quite successfully from PowerShell to run the same commands on many dozens of Linux servers, until now. Apparently because I've not tried to execute any programs that need " in them.

For example, this command works perfectly when passed to plink: : ; sudo -iu postgres ls -aFl.

This command... not so much:

": ; sudo -iu postgres psql -Xc `"SELECT datname FROM pg_database;`""

Note the backticks, to preserve the internal double quotes in PowerShell.

Any thoughts on how to fix this? (Everything is a variable because this code is in a function which builds a slightly different $TheCMD depending on which server I'm looking at.

Below is sample code demonstrating the error:

PS C:\Users> $Session = 'FIS-P-CDS-PGS-201'
PS C:\Users> $TheCMD = ": ; sudo -iu postgres psql -Xc `"SELECT datname FROM pg_database;`""
PS C:\Users> echo $TheCMD
: ; sudo -iu postgres psql -Xc "SELECT datname FROM pg_database;"
PS C:\Users>
PS C:\Users> plink -t -load "$Session" -batch $TheCMD
psql: warning: extra command-line argument "pg_database" ignored
psql: FATAL:  role "FROM" does not exist
PS C:\Users>
PS C:\Users>
PS C:\Users> $TheCMD = ": ; sudo -iu postgres ls -aFl"
PS C:\Users> plink -t -load "$Session" -batch $TheCMD
total 120
drwx------   8 postgres postgres  4096 Apr  7 16:36 ./
drwxr-xr-x. 35 root     root      4096 Nov  9  2021 ../
drwx------   4 postgres postgres    54 Nov 10  2021 9.6/
drwxr-xr-x   3 postgres postgres    24 Nov 26 06:48 backups/
[snip]

1 Answer 1

0

You might try resolving powershell variables as a separate step, prior to executing the commands in plink. There is a built in function callled ExpandString that will do this for you. Here is a line of code from a function I wrote:

          Get-Content $template |
               {$ExecutionContext.InvokeCommand.ExpandString($_)} 

This resolves powershell variables in the template before passing the expansion down the pipeline.

1
  • PS doesn't like that: Expressions are only allowed as the first element of a pipeline..
    – RonJohn
    Commented May 20 at 15:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .