Home > Blockchain >  Copy and unzip files from windows to remote linux machine - powershel script
Copy and unzip files from windows to remote linux machine - powershel script

Time:08-13

I have a ./build folder (inside a project on a Windows machine) that I need to compress and send to a remote Linux server where I need to unzip it.

Here's the cmdlet function that I wrote (it doesn't work as intended):

function scpFileFromBuildFolder {
param (
    [string]$userAndHost,
    [string]$targetDirectory,
)
Compress-Archive -Force -Path "./build/" -Destinationpath "./build/main.zip" -CompressionLevel Optimal
Write-Host -fore Cyan "`r`nCopying archive from ./build/ to ${targetDirectory}"
. scp "./build/main.zip" "${userAndHost}:${targetDirectory}"
Write-Host -fore Cyan "`r`nDecompressing archive on a remote directory:"
. ssh $userAndHost ". cd ${targetDirectory}"
. ssh $userAndHost ". unzip main"
. ssh $userAndHost ". cd build/"
. ssh $userAndHost ". find . -maxdepth 1 -exec mv {} .. \" # move all files to a parent dir
. ssh $userAndHost ". cd .."
. ssh $userAndHost ". rm -rf build build.zip main"
. ssh $userAndHost ". exit"

}

As you can see, I tried to perform multiple commands on a remote server via ssh. All of that works if I do things manually through PowerShell: I compress the file, scp it, and ssh to the server where I unzip the file and do all the other things. But it doesn't work this way through a .ps1 script — it only copies the file but doesn't do anything after the print statement ("Decompressing archive on a remote directory:").

Please, help me finish this function.

CodePudding user response:

You should only run ssh once, with any remote commands getting fed to ssh up through to exit. Otherwise it will just pause and wait for more commands. For example:

ssh $UserAndHost "cd /tmp; hostname; pwd; exit"

You can put them on separate lines like a bash script, BUT be careful of crlf line endings (or strip them):

Write-Host -fore Cyan "`r`nDecompressing archive on a remote directory:"
ssh $userAndHost "cd ${targetDirectory}
unzip main
cd build/
find . -maxdepth 1 -exec mv {} .. \ # move all files to a parent dir
cd ..
rm -rf build build.zip main
exit"

# ERROR if crlf like:
bash: line 1: $'\r': command not found
  • Related