Search code examples
powershellcygwinscp

Powershell - Run SCP command using CYGWIN but also expand variables


I need to expand variables before running the SCP command as a result I can't use single quote. If I run the script using double quotes in Powershell ISE it works fine.

But doesn't work if I run the script through command prompt.

I'm using zabbix to run the script which calls the script as [cmd /C "powershell -NoProfile -ExecutionPolicy Bypass -File .\myscript.ps1"]

Here is the code that needs to run SCP using Cygwin bash.

if ((test-path  "$zipFile"))

{ 

C:\cygwin\bin\bash.exe -l "set -x; scp /cygdrive/e/logs/$foldername/dir1/$foldername.zip root@10.10.10.10:~/"

}

Output:

/usr/bin/bash: set -x;  /cygdrive/e/logs/myfolder/dir1/server.zip root@10.10.10.10:~/: No such file or directory

If I run the same command above in Cygwin manually it works.

I even tried to use bash -l -c but then the SSH session is stuck maybe because the root@10.10.10.10 becomes $1 according to the documentation.

Documentation link

   -c        If the -c option is present, then commands are read from

             the first non-option argument command_string.  If there are

             arguments after the command_string, the first argument is

             assigned to $0 and any remaining arguments are assigned to

             the positional parameters.  The assignment to $0 sets the

             name of the shell, which is used in warning and error

             messages.

Solution

  • Figured it out. It was halting when using bash -c was due to StrictHostKeyChecking, the known hosts thing (where you get a prompt to type yes/no). I set the -v switch to SCP and it showed me the Debug logs where it was halting.

    Had to set scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null options.

    The complete line now looks like the following:

    c:\$cygwin_folder\bin\bash.exe -c ("/usr/bin/scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -v -i /cygdrive/c/cygwin/home/myuser/.ssh/id_rsa  /cygdrive/e/logs/$foldername/dir1/$foldername.zip root@10.10.10.10:~/")