functions/Set-DbaDatabaseState.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
Function Set-DbaDatabaseState
{
<#
.SYNOPSIS
Sets various options for databases, hereby called "states"
 
.DESCRIPTION
Sets some common "states" on databases:
 - "RW" options (ReadOnly, ReadWrite)
 - "Status" options (Online, Offline, Emergency, plus a special "Detached")
 - "Access" options (SingleUser, RestrictedUser, MultiUser)
 
Returns an object with SqlInstance, Database, RW, Status, Access, Notes
 
Notes gets filled when something went wrong setting the state
 
.PARAMETER SqlInstance
The SQL Server that you're connecting to
 
.PARAMETER Credential
Credential object used to connect to the SQL Server as a different user
 
.PARAMETER Database
Sets options only on these databases
 
.PARAMETER Exclude
Sets options for all but these specific databases
 
.PARAMETER AllDatabases
This is a parameter that was included for safety, so you don't accidentally set options on all databases without specifying
 
.PARAMETER ReadOnly
RW Option : Sets the database as READ_ONLY
 
.PARAMETER ReadWrite
RW Option : Sets the database as READ_WRITE
 
.PARAMETER Online
Status Option : Sets the database as ONLINE
 
.PARAMETER Offline
Status Option : Sets the database as OFFLINE
 
.PARAMETER Emergency
Status Option : Sets the database as EMERGENCY
 
.PARAMETER Detached
Status Option : Detaches the database
 
.PARAMETER SingleUser
Access Option : Sets the database as SINGLE_USER
 
.PARAMETER RestrictedUser
Access Option : Sets the database as RESTRICTED_USER
 
.PARAMETER MultiUser
Access Option : Sets the database as MULTI_USER
 
.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed.
 
.PARAMETER Confirm
Prompts you for confirmation before executing any changing operations within the command.
 
.PARAMETER Force
For most options, this translates to istantly rolling back any open transactions
that may be stopping the process.
For -Detached it is required to break mirroring and Availability Groups
 
.PARAMETER SmoDatabase
Internal parameter for piped objects - this will likely go away once we move to better dynamic parameters
  
.NOTES
Author: niphlod
 
dbatools PowerShell module (https://dbatools.io)
Copyright (C) 2016 Chrissy LeMaire
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.
 
.LINK
https://dbatools.io/Set-DbaDatabaseState
 
.EXAMPLE
Set-DbaDatabaseState -SqlServer sqlserver2014a -Database HR -Offline
 
Sets the HR database as OFFLINE
 
.EXAMPLE
Set-DbaDatabaseState -SqlServer sqlserver2014a -AllDatabases -Exclude HR -Readonly -Force
 
Sets all databases of the sqlserver2014a instance, except for HR, as READ_ONLY
 
.EXAMPLE
Get-DbaDatabaseState -SqlInstance sql2016 | Where-Object Status -eq 'Offline' | Set-DbaDatabaseState -Online
  
Finds all offline databases and sets them to online
 
.EXAMPLE
Set-DbaDatabaseState -SqlServer sqlserver2014a -Database HR -SingleUser
 
Sets the HR database as SINGLE_USER
 
.EXAMPLE
Set-DbaDatabaseState -SqlServer sqlserver2014a -Database HR -SingleUser -Force
 
Sets the HR database as SINGLE_USER, dropping all other connections (and rolling back open transactions)
 
#>

[CmdletBinding(DefaultParameterSetName = "Default", SupportsShouldProcess = $true)]
Param (
[parameter(Mandatory = $true, ValueFromPipelineByPropertyName, ParameterSetName = "Server")]
[Alias("ServerInstance", "SqlServer")]
[object[]]$SqlInstance,
[PSCredential][System.Management.Automation.CredentialAttribute()]
$Credential,
[switch]$AllDatabases,
[switch]$ReadOnly,
[switch]$ReadWrite,
[switch]$Online,
[switch]$Offline,
[switch]$Emergency,
[switch]$Detached,
[switch]$SingleUser,
[switch]$RestrictedUser,
[switch]$MultiUser,
[switch]$Force,
[parameter(Mandatory = $true, ValueFromPipeline, ParameterSetName = "Database")]
[PsCustomObject[]]$SmoDatabase
)

DynamicParam
{
if ($SqlInstance)
{
Get-ParamSqlDatabases -SqlInstance $SqlInstance[0] -SqlCredential $Credential -NoSystem
}
}

BEGIN
{
$databases = $psboundparameters.Databases
$exclude = $psboundparameters.Exclude

function Get-WrongCombo($optset, $allparams)
{
$x = 0
foreach ($opt in $optset)
{
if ($allparams.ContainsKey($opt)) { $x += 1 }
}
if ($x -gt 1)
{
$msg = $optset -Join ',-'
$msg = "You can only specify one of: -" + $msg
throw $msg
}
}

function Edit-DatabaseState($sqlinstance, $dbname, $opt, $immediate = $false)
{
$warn = $null
$sql = "ALTER DATABASE [$dbname] SET $opt"
if ($immediate)
{
$sql += " WITH ROLLBACK IMMEDIATE"
}
else
{
$sql += " WITH NO_WAIT"
}
try
{
Write-Verbose $sql
if ($immediate)
{
# this can be helpful only for SINGLE_USER databases
# but since $immediate is called, it does no more harm
# than the immediate rollback
$sqlinstance.KillAllProcesses($dbname)
}
$null = $sqlinstance.ConnectionContext.ExecuteNonQuery($sql)
}
catch
{
Write-Exception $_
$warn = "Failed to set '$dbname' to $opt"
Write-Warning $warn
}
return $warn
}

$UserAccessHash = @{
'Single' = 'SINGLE_USER'
'Restricted' = 'RESTRICTED_USER'
'Multiple' = 'MULTI_USER'
}
$ReadOnlyHash = @{
$true = 'READ_ONLY'
$false = 'READ_WRITE'
}
$StatusHash = @{
'Offline' = 'OFFLINE'
'Normal' = 'ONLINE'
'EmergencyMode' = 'EMERGENCY'
}

function Get-DbState($db)
{
$base = [PSCustomObject]@{
'Access' = $null
'Status' = $null
'RW' = $null
}
$base.RW = $ReadOnlyHash[$db.ReadOnly]
$base.Access = $UserAccessHash[$db.UserAccess.toString()]
foreach ($status in $StatusHash.Keys)
{
if ($db.Status -match $status)
{
$base.Status = $StatusHash[$status]
break
}
}
return $base
}

$RWExclusive = @('ReadOnly', 'ReadWrite')
$StatusExclusive = @('Online', 'Offline', 'Emergency', 'Detached')
$AccessExclusive = @('SingleUser', 'RestrictedUser', 'MultiUser')
$allparams = $PSBoundParameters
Get-WrongCombo -optset $RWExclusive -allparams $allparams
Get-WrongCombo -optset $StatusExclusive -allparams $allparams
Get-WrongCombo -optset $AccessExclusive -allparams $allparams

$dbs = @()
}
PROCESS
{
# use PROCESS to gather info, and END to execute on it
if ($databases.Length -eq 0 -and $AllDatabases -eq $false -and !$smodatabase)
{
throw "You must specify a -AllDatabases or -Database to continue"
}

if ($smodatabase)
{
$dbs += $smodatabase.Database
}
else
{
foreach ($instance in $SqlInstance)
{
Write-Verbose "Connecting to $instance"
try
{
$server = Connect-SqlServer -SqlServer $instance -SqlCredential $Credential
}
catch
{
Write-Warning "Can't connect to $instance"
Continue
}
$all_dbs = $server.Databases
$dbs += $all_dbs | Where-Object { @('master', 'model', 'msdb', 'tempdb', 'distribution') -notcontains $_.Name }

if ($databases.count -gt 0)
{
$dbs = $dbs | Where-Object { $databases -contains $_.Name }
}
if ($exclude.count -gt 0)
{
$dbs = $dbs | Where-Object { $exclude -notcontains $_.Name }
}
}
}
}

END
{
if ($Detached -eq $true)
{
# we need to see what snaps are on the server, as base databases cannot be dropped
$snaps = $dbs | Where-Object { $_.DatabaseSnapshotBaseName.Length -gt 0 }
$snaps = $snaps | Select-Object -ExpandProperty DatabaseSnapshotBaseName | Get-Unique
}

# need to pick up here
foreach ($db in $dbs)
{
$db_status = Get-DbState $db

# normalizing properties returned by SMO to something more "fixed"
$warn = @()

if ($db.DatabaseSnapshotBaseName.Length -gt 0)
{
Write-Warning "Database $db is a snapshot, skipping"
Continue
}

if (!$Force)
{
if ($ReadOnly, $Offline, $Emergency, $SingleUser, $RestrictedUser, $Detached -contains $true)
{
if (Get-DbaProcess -SqlServer $server -SqlCredential $Credential -Databases $db.name)
{
Write-Warning "Users are currently connected to the database $db and Force was not specified. Skipping."
continue
}
}
}

if ($ReadOnly -eq $true)
{
if ($db_status.RW -eq 'READ_ONLY')
{
Write-Verbose "Database $db is already READ_ONLY"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to READ_ONLY"))
{
Write-Verbose "Setting database $db to READ_ONLY"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "READ_ONLY" -immediate $Force
}
}
}

if ($ReadWrite -eq $true)
{
if ($db_status.RW -eq 'READ_WRITE')
{
Write-Verbose "Database $db is already READ_WRITE"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to READ_WRITE"))
{
Write-Verbose "Setting database $db to READ_WRITE"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "READ_WRITE" -immediate $Force
}
}
}

if ($Online -eq $true)
{
if ($db_status.Status -eq 'ONLINE')
{
Write-Verbose "Database $db is already ONLINE"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to ONLINE"))
{
Write-Verbose "Setting database $db to ONLINE"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "ONLINE" -immediate $Force
}
}
}

if ($Offline -eq $true)
{
if ($db_status.Status -eq 'OFFLINE')
{
Write-Verbose "Database $db is already OFFLINE"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to OFFLINE"))
{
Write-Verbose "Setting database $db to OFFLINE"
$warn = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "OFFLINE" -immediate $Force
}
}
}

if ($Emergency -eq $true)
{
if ($db_status.Status -eq 'EMERGENCY')
{
Write-Verbose "Database $db is already EMERGENCY"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to EMERGENCY"))
{
Write-Verbose "Setting database $db to EMERGENCY"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "EMERGENCY" -immediate $Force
}
}
}

if ($SingleUser -eq $true)
{
if ($db_status.Access -eq 'SINGLE_USER')
{
Write-Verbose "Database $db is already SINGLE_USER"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to SINGLE_USER"))
{
Write-Verbose "Setting $db to SINGLE_USER"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "SINGLE_USER" -immediate $Force
}
}
}

if ($RestrictedUser -eq $true)
{
if ($db_status.Access -eq 'RESTRICTED_USER')
{
Write-Verbose "Database $db is already RESTRICTED_USER"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to RESTRICTED_USER"))
{
Write-Verbose "Setting $db to RESTRICTED_USER"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "RESTRICTED_USER" -immediate $Force
}
}
}

if ($MultiUser -eq $true)
{
if ($db_status.Access -eq 'MULTI_USER')
{
Write-Verbose "Database $db is already MULTI_USER"
}
else
{
If ($Pscmdlet.ShouldProcess($instance, "Set $db to MULTI_USER"))
{
Write-Verbose "Setting $db to MULTI_USER"
$warn += Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "MULTI_USER" -immediate $Force
}
}
}

# Refresh info about database state here (before detaching)
$db.Refresh()

if ($Detached -eq $true)
{
if ($db.Name -in $snaps)
{
Write-Warning "Database $db has snapshots, you need to drop them before detaching, skipping..."
Continue
}
if ($db.IsMirroringEnabled -eq $true -or $db.AvailabilityGroupName.Length -gt 0)
{
if ($Force -eq $false)
{
Write-Warning "Needs -Force to detach $db, skipping"
Continue
}
}

if ($db.IsMirroringEnabled)
{
If ($Pscmdlet.ShouldProcess($instance, "Break mirroring for $db"))
{
try
{
$db.ChangeMirroringState([Microsoft.SqlServer.Management.Smo.MirroringOption]::Off)
$db.Alter()
$db.Refresh()
Write-Verbose "Broke mirroring for $db"
}
catch
{
Write-Warning "Could not break mirror for $db. Skipping."
Write-Exception $_
Continue
}
}
}

if ($database.AvailabilityGroupName.Length -gt 0)
{
$agname = $db.AvailabilityGroupName
If ($Pscmdlet.ShouldProcess($instance, "Removing $db from AG [$agname]"))
{
try
{
$server.AvailabilityGroups[$db.AvailabilityGroupName].AvailabilityDatabases[$db.Name].Drop()
Write-Verbose "Successfully removed $db from AG [$agname] on $server"
}
catch
{
Write-Warning "Could not remove $db from AG [$agname] on $server"
Write-Exception $_
Continue
}
}
}

# DBA 101 should encourage detaching just OFFLINE databases
# we can do that here
If ($Pscmdlet.ShouldProcess($instance, "Detaching $db"))
{
if ($db_status.Status -ne 'OFFLINE')
{
$opstatus = Edit-DatabaseState -sqlinstance $server -dbname $db.Name -opt "OFFLINE" -immediate $true
}
try
{
$sql = "EXEC master.dbo.sp_detach_db N$db"
Write-Verbose $sql
$null = $server.ConnectionContext.ExecuteNonQuery($sql)
$newstate.Status = 'DETACHED'
}
catch
{
Write-Exception $_
Write-Warning "Failed to detach $db"
$warn += "Failed to detach"
}
}

}
if ($warn.Count -gt 0)
{
$warn = $warn | Get-Unique
$warn = $warn -Join ';'
}
else
{
$warn = $null
}

$db.Refresh()
$newstate = Get-DbState $db

[PSCustomObject]@{
SqlInstance = $server.Name
InstanceName = $server.ServiceName
ComputerName = $server.NetName
DatabaseName = $db.Name
RW = $newstate.RW
Status = $newstate.Status
Access = $newstate.Access
Notes = $warn
Database = $db
} | Select-DefaultView -ExcludeProperty Database
}
}

}