Skip to content

Instantly share code, notes, and snippets.

@chadbaldwin
Last active March 6, 2023 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chadbaldwin/1a486b4fbf48e9b0cd9551cb7e16382a to your computer and use it in GitHub Desktop.
Save chadbaldwin/1a486b4fbf48e9b0cd9551cb7e16382a to your computer and use it in GitHub Desktop.
Using Docker, create a SQL Server container, or start one of it already exists.
# Start SQL Server docker instance
function Start-SQLServer {
param (
[Parameter()][string]$Tag = 'latest'
)
$containerName = 'sqlserver'
$sa_password = 'yourStrong(!)Password'
$container = docker inspect $containerName | ConvertFrom-Json
# create & start
if ($null -eq $container) {
docker run `
-d `
--name $containerName `
-e 'ACCEPT_EULA=Y' -e "SA_PASSWORD=${sa_password}" `
-p 1433:1433 `
"mcr.microsoft.com/mssql/server:${Tag}"
write "Container '${containerName}' container has been created and started"
}
else {
$Tag = $container.Config.Image
# start
if ($container.State.Status -eq 'exited') {
docker start $containerName
write "Container '${containerName}' was already created and has been started"
}
# do nothing
elseif ($container.State.Status -eq 'running') {
write "Container '${containerName}' is already running"
}
$sa_password = (($container.Config.Env | ? { $_ -match 'SA_PASSWORD' }) -split '=')[1]
}
write '','Waiting until database is available...'
while ($true) {
sqlcmd -U sa -P $sa_password -S localhost -l 1 -t 1 -Q 'SELECT 1' *>&1 | Out-Null
if ($LASTEXITCODE -eq 0) { break }
sleep 1
}
$container = docker inspect $containerName | ConvertFrom-Json
write '',"Image: ${Tag}",'',"SQL Server Version: $($container.Config.Labels.'com.microsoft.version')",''
scb $sa_password
write 'Password copied to clipboard:',' Username: sa'," Password: ${sa_password}"
}
Register-ArgumentCompleter -CommandName Start-SQLServer -ParameterName Tag -ScriptBlock {
(irm 'https://mcr.microsoft.com/v2/mssql/server/tags/list').tags | ? { $_ -match 'latest' }
}
@chadbaldwin
Copy link
Author

[reserving first comment]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment