Recently, we were deploying a few resources in Microsoft Azure, and we needed to containerize some long running Powershell scripts in a utility Ubuntu Linux VM.
One way we came up with to do this was to utilize the Microsoft Powershell Docker Container running a startup script to launch scripts in the $CWD/scripts folder.
Just drop your long running Powershell script (preferably with an infinite loop and some kind of try/catch block) in the scripts directory, and run the bash script below.
The result? Easy to deploy, long running PowerShell daemon scripts in Docker! (Also works on Windows with WSL)
#!/bin/bash
# Directory containing your PowerShell scripts
SCRIPTS_DIR="$PWD/scripts"
# Docker image to use
DOCKER_IMAGE="mcr.microsoft.com/azure-powershell"
# Loop through each PowerShell script in the scripts directory
for script in "$SCRIPTS_DIR"/*.ps1
do
if [ -f "$script" ]; then
# Extract filename for container naming
filename=$(basename -- "$script")
# Check if a container with the same name exists
existing_container=$(docker ps -a -q -f name="$filename")
if [ ! -z "$existing_container" ]; then
echo "Stopping and removing existing container: $filename"
docker stop "$filename"
docker rm "$filename"
fi
# Run the script in a new Docker container
echo "Running $filename in a new container..."
docker run --name "$filename" --rm -d \
-v "$PWD/scripts/:/scripts" \
--log-opt max-size=50m \
$DOCKER_IMAGE pwsh -File "/scripts/$filename"
fi
done
echo "All scripts have been executed."