commands

^

New-DbaAvailabilityGroup

Author Chrissy LeMaire (@cl), netnerds.net
Availability Windows, Linux, macOS

 

Want to see the source code for this command? Check out New-DbaAvailabilityGroup on GitHub.
Want to see the Bill Of Health for this command? Check out New-DbaAvailabilityGroup.

Synopsis

Automates the creation of availability groups.

Description

Automates the creation of availability groups.

  • Checks prerequisites
  • Creates Availability Group and adds primary replica
  • Grants cluster permissions if necessary
  • Adds secondary replica if supplied
  • Adds databases if supplied
    • Performs backup/restore if seeding mode is manual
    • Database has to be in full recovery mode (so at least one backup has been taken) if seeding mode is automatic
  • Adds listener to primary if supplied
  • Joins secondaries to availability group
  • Grants endpoint connect permissions to service accounts
  • Grants CreateAnyDatabase permissions if seeding mode is automatic
  • Returns Availability Group object from primary

NOTES:

  • If a backup / restore is performed, the backups will be left intact on the network share.
  • If you're using SQL Server on Linux and a fully qualified domain name is required, please use the FQDN to create a proper Endpoint

PLEASE NOTE THE CHANGED DEFAULTS:
Starting with version 1.1.x we changed the defaults of the following parameters to have the same defaults
as the T-SQL command "CREATE AVAILABILITY GROUP" and the wizard in SQL Server Management Studio:

  • ClusterType from External to Wsfc (Windows Server Failover Cluster).
  • FailureConditionLevel from OnServerDown (Level 1) to OnCriticalServerErrors (Level 3).
  • ConnectionModeInSecondaryRole from AllowAllConnections (ALL) to AllowNoConnections (NO).
    To change these defaults we have introduced configuration parameters for all of them, see documentation of the parameters for details.

Thanks for this, Thomas Stringer! https://blogs.technet.microsoft.com/heyscriptingguy/2013/04/29/set-up-an-alwayson-availability-group-with-powershell/

Syntax

New-DbaAvailabilityGroup
    [[-Primary] <DbaInstanceParameter>]
    [[-PrimarySqlCredential] <PSCredential>]
    [[-Secondary] <DbaInstanceParameter[]>]
    [[-SecondarySqlCredential] <PSCredential>]
    [-Name] <String>
    [-IsContained]
    [-ReuseSystemDatabases]
    [-DtcSupport]
    [[-ClusterType] <String>]
    [[-AutomatedBackupPreference] <String>]
    [[-FailureConditionLevel] <String>]
    [[-HealthCheckTimeout] <Int32>]
    [-Basic]
    [-DatabaseHealthTrigger]
    [-Passthru]
    [[-Database] <String[]>]
    [[-SharedPath] <String>]
    [-UseLastBackup]
    [-Force]
    [[-AvailabilityMode] <String>]
    [[-FailoverMode] <String>]
    [[-BackupPriority] <Int32>]
    [[-ConnectionModeInPrimaryRole] <String>]
    [[-ConnectionModeInSecondaryRole] <String>]
    [[-SeedingMode] <String>]
    [[-Endpoint] <String>]
    [[-EndpointUrl] <String[]>]
    [[-Certificate] <String>]
    [-ConfigureXESession]
    [[-IPAddress] <IPAddress[]>]
    [[-SubnetMask] <IPAddress>]
    [[-Port] <Int32>]
    [-Dhcp]
    [-EnableException]
    [-WhatIf]
    [-Confirm]
    [<CommonParameters>]

 

Examples

 

Example: 1
PS C:\> New-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint

Creates a new availability group on sql2016a named SharePoint

Example: 2
PS C:\> New-DbaAvailabilityGroup -Primary sql2016a -Name SharePoint -Secondary sql2016b

Creates a new availability group on sql2016a named SharePoint with a secondary replica, sql2016b

Example: 3
PS C:\> New-DbaAvailabilityGroup -Primary sql2016std -Name BAG1 -Basic -Confirm:$false

Creates a basic availability group named BAG1 on sql2016std and does not confirm when setting up

Example: 4
PS C:\> New-DbaAvailabilityGroup -Primary sql2022n01 -Secondary sql2022n02 -Name AgContained -IsContained

Creates a contained availability group named AgContained on nodes sql2022n01 and sql2022n02

Example: 5
PS C:\> New-DbaAvailabilityGroup -Primary sql2016b -Name AG1 -Dhcp -Database db1 -UseLastBackup

Creates an availability group on sql2016b with the name ag1. Uses the last backups available to add the database db1 to the AG.

Example: 6
PS C:\> New-DbaAvailabilityGroup -Primary sql2017 -Name SharePoint -ClusterType None -FailoverMode Manual

Creates a new availability group on sql2017 named SharePoint with a cluster type of none and a failover mode of manual

Example: 7
PS C:\> New-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -ClusterType None -SeedingMode Automatic -FailoverMode Manual

Creates a new availability group with a primary replica on sql1 and a secondary on sql2. Automatically adds the database pubs.

Example: 8
PS C:\> New-DbaAvailabilityGroup -Primary sql1 -Secondary sql2 -Name ag1 -Database pubs -EndpointUrl 'TCP://sql1.specialnet.local:5022', 'TCP://sql2.specialnet.local:5022'

Creates a new availability group with a primary replica on sql1 and a secondary on sql2 with custom endpoint urls. Automatically adds the database pubs.

Example: 9
PS C:\> $cred = Get-Credential sqladmin
PS C:\> $params = @{
>> Primary = "sql1"
>> PrimarySqlCredential = $cred
>> Secondary = "sql2"
>> SecondarySqlCredential = $cred
>> Name = "test-ag"
>> Database = "pubs"
>> ClusterType = "None"
>> SeedingMode = "Automatic"
>> FailoverMode = "Manual"
>> Confirm = $false
>> }
PS C:\> New-DbaAvailabilityGroup @params

This exact command was used to create an availability group on docker!

Required Parameters

-Name

The name of the Availability Group.

Alias
Required True
Pipeline false
Default Value

Optional Parameters

-Primary

The primary SQL Server instance. Server version must be SQL Server version 2012 or higher.

Alias
Required False
Pipeline true (ByValue)
Default Value
-PrimarySqlCredential

Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).
Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.
For MFA support, please use Connect-DbaInstance.

Alias
Required False
Pipeline false
Default Value
-Secondary

The target SQL Server instance or instances. Server version must be SQL Server version 2012 or higher.

Alias
Required False
Pipeline false
Default Value
-SecondarySqlCredential

Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).
Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.
For MFA support, please use Connect-DbaInstance.

Alias
Required False
Pipeline false
Default Value
-IsContained

Builds the Availability Group as contained. Only supported in SQL Server 2022 or higher.
https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/contained-availability-groups-overview

Alias
Required False
Pipeline false
Default Value False
-ReuseSystemDatabases

Used when rebuilding an availability group with the same name, where system databases already exist for the contained availability group.

Alias
Required False
Pipeline false
Default Value False
-DtcSupport

Indicates whether the DtcSupport is enabled

Alias
Required False
Pipeline false
Default Value False
-ClusterType

Cluster type of the Availability Group. Only supported in SQL Server 2017 and above.
Options include: Wsfc, External or None.
Defaults to Wsfc (Windows Server Failover Cluster).
The default can be changed with:
Set-DbatoolsConfig -FullName 'AvailabilityGroups.Default.ClusterType' -Value '...' -Passthru | Register-DbatoolsConfig

Alias
Required False
Pipeline false
Default Value (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.ClusterType' -Fallback 'Wsfc')
Accepted Values Wsfc,External,None
-AutomatedBackupPreference

Specifies how replicas in the primary role are treated in the evaluation to pick the desired replica to perform a backup.

Alias
Required False
Pipeline false
Default Value Secondary
Accepted Values None,Primary,Secondary,SecondaryOnly
-FailureConditionLevel

Specifies the different conditions that can trigger an automatic failover in Availability Group.
Defaults to OnCriticalServerErrors (Level 3).
From https://docs.microsoft.com/en-us/sql/t-sql/statements/create-availability-group-transact-sql:
Level 1 = OnServerDown
Level 2 = OnServerUnresponsive
Level 3 = OnCriticalServerErrors (the default in CREATE AVAILABILITY GROUP and in this command)
Level 4 = OnModerateServerErrors
Level 5 = OnAnyQualifiedFailureCondition
The default can be changed with:
Set-DbatoolsConfig -FullName 'AvailabilityGroups.Default.FailureConditionLevel' -Value 'On...' -Passthru | Register-DbatoolsConfig

Alias
Required False
Pipeline false
Default Value (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.FailureConditionLevel' -Fallback 'OnCriticalServerErrors')
Accepted Values OnAnyQualifiedFailureCondition,OnCriticalServerErrors,OnModerateServerErrors,OnServerDown,OnServerUnresponsive
-HealthCheckTimeout

This setting used to specify the length of time, in milliseconds, that the SQL Server resource DLL should wait for information returned by the sp_server_diagnostics stored procedure before reporting
the Always On Failover Cluster Instance (FCI) as unresponsive.
Changes that are made to the timeout settings are effective immediately and do not require a restart of the SQL Server resource.
Defaults to 30000 (30 seconds).

Alias
Required False
Pipeline false
Default Value 30000
-Basic

Indicates whether the availability group is Basic Availability Group.
https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/basic-availability-groups-always-on-availability-groups

Alias
Required False
Pipeline false
Default Value False
-DatabaseHealthTrigger

Indicates whether the availability group triggers the database health.

Alias
Required False
Pipeline false
Default Value False
-Passthru

Don't create the availability group, just pass thru an object that can be further customized before creation.

Alias
Required False
Pipeline false
Default Value False
-Database

The database or databases to add.

Alias
Required False
Pipeline false
Default Value
-SharedPath

The network share where the backups will be backed up and restored from.
Each SQL Server service account must have access to this share.
NOTE: If a backup / restore is performed, the backups will be left in tact on the network share.

Alias
Required False
Pipeline false
Default Value
-UseLastBackup

Use the last full and log backup of database. A log backup must be the last backup.

Alias
Required False
Pipeline false
Default Value False
-Force

Drop and recreate the database on remote servers using fresh backup.

Alias
Required False
Pipeline false
Default Value False
-AvailabilityMode

Sets the availability mode of the availability group replica. Options are: AsynchronousCommit and SynchronousCommit. SynchronousCommit is default.

Alias
Required False
Pipeline false
Default Value SynchronousCommit
Accepted Values AsynchronousCommit,SynchronousCommit
-FailoverMode

Sets the failover mode of the availability group replica. Options are Automatic, Manual and External. Automatic is default.

Alias
Required False
Pipeline false
Default Value Automatic
Accepted Values Automatic,Manual,External
-BackupPriority

Sets the backup priority availability group replica. Default is 50.

Alias
Required False
Pipeline false
Default Value 50
-ConnectionModeInPrimaryRole

Specifies the connection intent modes of an Availability Replica in primary role. AllowAllConnections by default.

Alias
Required False
Pipeline false
Default Value AllowAllConnections
Accepted Values AllowAllConnections,AllowReadWriteConnections
-ConnectionModeInSecondaryRole

Specifies the connection modes of an Availability Replica in secondary role.
Options include: AllowNoConnections (Alias: No), AllowReadIntentConnectionsOnly (Alias: Read-intent only), AllowAllConnections (Alias: Yes)
Defaults to AllowNoConnections.
The default can be changed with:
Set-DbatoolsConfig -FullName 'AvailabilityGroups.Default.ConnectionModeInSecondaryRole' -Value '...' -Passthru | Register-DbatoolsConfig

Alias
Required False
Pipeline false
Default Value (Get-DbatoolsConfigValue -FullName 'AvailabilityGroups.Default.ConnectionModeInSecondaryRole' -Fallback 'AllowNoConnections')
Accepted Values AllowNoConnections,AllowReadIntentConnectionsOnly,AllowAllConnections,No,Read-intent only,Yes
-SeedingMode

Specifies how the secondary replica will be initially seeded.
Automatic enables direct seeding. This method will seed the secondary replica over the network. This method does not require you to backup and restore a copy of the primary database on the replica.
Manual requires you to create a backup of the database on the primary replica and manually restore that backup on the secondary replica.

Alias
Required False
Pipeline false
Default Value Manual
Accepted Values Automatic,Manual
-Endpoint

By default, this command will attempt to find a DatabaseMirror endpoint. If one does not exist, it will create it.
If an endpoint must be created, the name "hadr_endpoint" will be used. If an alternative is preferred, use Endpoint.

Alias
Required False
Pipeline false
Default Value
-EndpointUrl

By default, the property Fqdn of Get-DbaEndpoint is used as EndpointUrl.
Use EndpointUrl if different URLs are required due to special network configurations.
EndpointUrl has to be an array of strings in format 'TCP://system-address:port', one entry for every instance.
First entry for the primary instance, following entries for secondary instances in the order they show up in Secondary.
See details regarding the format at: https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/specify-endpoint-url-adding-or-modifying-availability-replica

Alias
Required False
Pipeline false
Default Value
-Certificate

Specifies that the endpoint is to authenticate the connection using the certificate specified by certificate_name to establish identity for authorization.
The far endpoint must have a certificate with the public key matching the private key of the specified certificate.

Alias
Required False
Pipeline false
Default Value
-ConfigureXESession

Configure the AlwaysOn_health extended events session to start automatically on every replica as the SSMS wizard would do.
https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-extended-events#BKMK_alwayson_health

Alias
Required False
Pipeline false
Default Value False
-IPAddress

Sets the IP address of the availability group listener.

Alias
Required False
Pipeline false
Default Value
-SubnetMask

Sets the subnet IP mask of the availability group listener.

Alias
Required False
Pipeline false
Default Value 255.255.255.0
-Port

Sets the number of the port used to communicate with the availability group.

Alias
Required False
Pipeline false
Default Value 1433
-Dhcp

Indicates whether the object is DHCP.

Alias
Required False
Pipeline false
Default Value False
-EnableException

By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

Alias
Required False
Pipeline false
Default Value False
-WhatIf

Shows what would happen if the command were to run. No actions are actually performed.

Alias wi
Required False
Pipeline false
Default Value
-Confirm

Prompts you for confirmation before executing any changing operations within the command.

Alias cf
Required False
Pipeline false
Default Value