Skip to content

Instantly share code, notes, and snippets.

@PCfromDCSnippets
Last active January 5, 2016 18:17
Show Gist options
  • Save PCfromDCSnippets/4b7e985551894907413a to your computer and use it in GitHub Desktop.
Save PCfromDCSnippets/4b7e985551894907413a to your computer and use it in GitHub Desktop.
Take DB Offline
#region Take DB Offline
# Set DB OFFLINE (Rollback is set to IMMEDIATE)
$query2 = "ALTER DATABASE [" + $dbName + "] SET OFFLINE WITH ROLLBACK IMMEDIATE;"
Write-Verbose "Taking [$dbName] Offline..." -Verbose
Invoke-Sqlcmd -Query $query2
# Get DB Status
function getDBStatus ($dbName) {
$query3 = "SELECT DATABASEPROPERTYEX('" + $dbName + "', 'Status') AS dbStatus"
$dbStatus = Invoke-Sqlcmd -Query $query3
return $dbStatus
}
# Wait until DB goes OFFLINE (which shouldn't be needed since ROLLBACK is set to IMMEDIATE)
Write-Verbose "Getting [$dbName] status..." -Verbose
$status = getDBStatus -dbName $dbName
Write-Output $status
$time = 0
while(-not ($status.dbStatus -eq "OFFLINE")){
sleep 2;
$time = $time + 2
Write-Verbose "Still waiting on DB to go OFFLINE... ($time seconds elapsed)" -Verbose
$status = getDBStatus -dbName $dbname
if ($time -gt 28) {
break
}
}
#endregion
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment