I have a Powershell script in which I need to know if Docker Desktop is currently running.
I have read that one way to do it is to use docker ps
and see if I get back a container list or an error message. But I'm struggling to make use of this in an actual script. I haven't worked out how to capture and act on the result correctly.
Here's what I have so far:
function IsDockerDesktopRunning()
{
$dockerPsResult = docker ps | Out-String
Write-Host "Result is:"
Write-Host $dockerPsResult
if (($dockerPsResult).StartsWith("error"))
{
return $false
}
return $true
}
$isRunning = IsDockerDesktopRunning
Write-Host $isRunning
When when it's not running, the result looks like this:
error during connect: This error may indicate that the docker daemon is not running.: Get "http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/containers/json": open //./pipe/docker_engine: The system cannot find the file specified.
Result is:
True
As you can see, it looks the output from the docker ps
command gets output as it's executed and the variable isn't populated.
Is there a way to correctly capture the output? Or, should I tackle the problem a different way?
To capture the error output as well, redirect stderr to stdout like this.
$docker = docker ps 2>&1
You can use this to determine if docker desktop is running.
if((docker ps 2>&1) -match '^(?!error)'){
Write-Host "Docker is running"
}