dataplat / dbatools

🚀 SQL Server automation and instance migrations have never been safer, faster or freer
https://dbatools.io
MIT License
2.39k stars 787 forks source link

Add command to set the instance authentication mode #9349

Closed bilodeauj closed 1 month ago

bilodeauj commented 1 month ago

Summarize Command's Functionality

Sometimes after having installed SQL Server there may be a need to change the authentication mode, let's say from Windows to Mixed Mode. I was unable to find an existing command in dbatools that allowed me change the Authentication Mode in SQL Server. The cmdlet should have the ability to provide a list list of sql instance, along with the desired Authentication mode and specify if the services should be restarted following the change in order for it to take effect.

Is there a command that is similiar or close to what you are looking for?

No

Technical Details

Here is some code i came up with and figured i'd share it back in the hopes that it might be useful to others, and might be able to be integrated into dbatools

function Set-DbaInstanceAuthenticationMode
{
    [CmdletBinding(SupportsShouldProcess, ConfirmImpact='Medium')]
    Param
    (
        [Parameter(ValueFromPipeline)]
        [DbaInstanceParameter[]]$SqlInstance,

        [PSCredential]$SqlCredential,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [ValidateSet('Integrated','Mixed','Normal')]
        [string]$AuthenticationMode,

        [switch]$Restart,

        [switch]$EnableException
    )

    Begin
    {
    }
    Process
    {

        foreach ($instance in $SqlInstance) {

            try {
                $server = Connect-DbaInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            if($server.Settings.LoginMode -ne $AuthenticationMode){
                if ($pscmdlet.ShouldProcess($server, "Change Authentication Mode from $($server.Settings.LoginMode) to $AuthenticationMode."))
                {
                    try {
                        $server.Settings.LoginMode = [Microsoft.SqlServer.Management.SMO.ServerLoginMode] $AuthenticationMode
                        $server.Settings.Alter()

                        if($Restart){
                            Restart-DbaService -SqlInstance $instance
                        }

                    } catch {
                        Stop-Function -Message "Could not modify Authentication Mode for $server" -ErrorRecord $_ -Target $server -Continue
                    }
                }
            } else {
                Write-Message -Level Verbose -Message "Skipping : Athentication Mode is already set to $AuthenticationMode "
            }
        }
    }
}

Set-DbaInstanceAuthenticationMode -SqlInstance "server01.domain.local" -AuthenticationMode Mixed -Restart