DockerTip #2 – How to Check if PowerShell is Running in a Docker Container?

As you may probably know, PowerShell can run in a Docker Container. Sometimes it can be useful to check if PowerShell is running inside a Docker Container instance before running a script for example. Then you can use this command:

PS C:\> Get-Service -Name cexecsvc

Status   Name               DisplayName
------   ----               -----------
Running  cexecsvc           Container Execution Agent

The option is to check if the service cexecsvc exist. If yes then it means that you are inside a Docker Container because this service only exists inside Docker containers.

You can easily create a PowerShell function:

Function Test-InsideDockerContainer {
  $DockerSvc = Get-Service -Name cexecsvc -ErrorAction SilentlyContinue
  if($DockerSvc -eq $null ) {
    return $false
  }
  else {
    return $true
  }
}

On my Container Host:

 

Thanks for reading! You can follow me on Twitter @PrigentNico

About Nicolas 282 Articles
I work as an IT Production Manager, based in Paris (France) with a primary focus on Microsoft technologies. I have 10 years experience in administering Windows Servers. . I am a Microsoft MVP for Cloud & Datacenter Management. I also received the PowerShell Hero 2016 award by PowerShell.0rg. And finally, I am "MCSE: Cloud Platform and Infrastructure", "MCSA: Windows Servers", "Administering & Deploying SCCM", and CheckPoint CCSA certified.