Skip to content

Commit 8c350e0

Browse files
Remove-DbaAvailabilityGroup - Improve AG removal for cluster type and version (#9952)
1 parent 7ef0f7e commit 8c350e0

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,4 @@ allcommands.ps1
5858
/.aitools
5959
.aider*
6060
/.shadowgit.git
61+
/.claude

public/Remove-DbaAvailabilityGroup.ps1

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,11 +98,40 @@ function Remove-DbaAvailabilityGroup {
9898
if ($SqlInstance) {
9999
$InputObject += Get-DbaAvailabilityGroup -SqlInstance $SqlInstance -SqlCredential $SqlCredential -AvailabilityGroup $AvailabilityGroup
100100
}
101+
101102
foreach ($ag in $InputObject) {
102-
if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Removing availability group $ag")) {
103-
# avoid enumeration issues
103+
$clusterType = 'WSFC'
104+
try {
105+
$result = $ag.Parent.Query("SELECT cluster_type_desc FROM sys.availability_groups WHERE name = N'$($ag.Name)'")
106+
if ($result -and $result.cluster_type_desc) { $clusterType = $result.cluster_type_desc }
107+
} catch { $clusterType = 'WSFC' }
108+
109+
$majorVersion = [int]($ag.Parent.Query("SELECT CAST(SERVERPROPERTY('ProductMajorVersion') AS int) AS v").v)
110+
111+
if ($clusterType -eq 'WSFC') {
112+
try {
113+
$isClustered = $ag.Parent.Query("SELECT CONVERT(bit, SERVERPROPERTY('IsClustered')) AS IsClustered").IsClustered
114+
if (-not $isClustered -and -not $Force) {
115+
Write-Warning "Skipping $($ag.Name): WSFC-type AG but instance not clustered. Use -Force to remove anyway."
116+
continue
117+
}
118+
} catch {
119+
if (-not $Force) {
120+
Write-Warning "Skipping $($ag.Name): unable to determine cluster state. Use -Force to ignore."
121+
continue
122+
}
123+
}
124+
}
125+
126+
if ($Pscmdlet.ShouldProcess($ag.Parent.Name, "Removing availability group $($ag.Name)")) {
104127
try {
105-
$ag.Parent.Query("DROP AVAILABILITY GROUP $ag")
128+
# For SQL 2017+ non-clustered AGs, append WITH (CLUSTER_TYPE = NONE)
129+
if ($majorVersion -ge 14 -and ($clusterType -eq 'NONE' -or -not $isClustered)) {
130+
$ag.Parent.Query("DROP AVAILABILITY GROUP [$($ag.Name)] WITH (CLUSTER_TYPE = NONE)")
131+
} else {
132+
$ag.Parent.Query("DROP AVAILABILITY GROUP [$($ag.Name)]")
133+
}
134+
106135
[PSCustomObject]@{
107136
ComputerName = $ag.ComputerName
108137
InstanceName = $ag.InstanceName

0 commit comments

Comments
 (0)