I am fairly new to powershell coding and fiddled around a bit, after learning some basics in here.
I wanted to store the success message in a variable after running following command:
docker cp <dockerid>:path/file localpath/file
It returns:
Successfully copied 13.8kB to localpathfile
Thats what i did in a script:
$return = docker cp <dockerid>:path/file localpath/file
The file gets copied, but the variable $return is empty afterwards.
What i dont understand is, i used something similar already:
$dockerID = docker ps -a -q --filter name=^/$containername$
and that one does work and $dockerID is filled afterwards.
Does anybody know the reason?
3
The reason $return
is empty is likely because your command did not exit properly with code 0
, and therefore, did not return the stdout
stream. This suggests that, despite the file being copied, an error occurred causing the command to exit with code 1
, returning the stderr
stream instead.
The PowerShell variable will only populate if the command successfully returns stdout
.
If you really want to populate the variable (despite the command giving error), you would need to redirect the stderr
stream to stdout
stream by using 2>&1
:
$return = docker cp <dockerid>:path/file localpath/file 2>&1
However, this may not be good advice if you’re new to PowerShell, as it’s important to learn how to handle errors when calling external commands. For example, you can use $LASTEXITCODE
to check the exit status.
$return = docker cp <dockerid>:path/file localpath/file
if ($LASTEXITCODE -ne 0) {
throw "The 'docker cp' command had errors"
}
If your command exits successfully with code 0
and returns stdout
, then $return
will be populated. Otherwise, if an error occurs, the if statement will catch it, and throw
will trigger a terminating error, stopping the script’s execution.