functions/Test-DbaConnection.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
#ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#

function Test-DbaConnection {
    <#
  .SYNOPSIS
   Tests the connection to a single instance.
 
  .DESCRIPTION
   Tests the ability to connect to an SQL Server instance outputting information about the server and instance.
 
  .PARAMETER SqlInstance
   The SQL Server Instance to test connection
 
  .PARAMETER Credential
   Credential object used to connect to the Computer as a different user
 
  .PARAMETER SqlCredential
   Allows you to login to servers using SQL Logins as opposed to Windows Auth/Integrated/Trusted. To use:
 
   $scred = Get-Credential, then pass $scred object to the -SqlCredential parameter.
 
   Windows Authentication will be used if SqlCredential is not specified. SQL Server does not accept Windows credentials being passed as credentials. To connect as a different Windows user, run PowerShell as that user.
 
  .PARAMETER Silent
   Replaces user friendly yellow warnings with bloody red exceptions of doom!
   Use this if you want the function to throw terminating errors you want to catch.
 
  .EXAMPLE
   Test-DbaConnection SQL2016
 
   ComputerName : SQL2016
   InstanceName : MSSQLSERVER
   SqlInstance : sql2016
   SqlVersion : 13.0.4001
   ConnectingAsUser : BASE\ctrlb
   ConnectSuccess : True
   AuthType : Windows Authentication
   AuthScheme : KERBEROS
   TcpPort : 1433
   IPAddress : 10.2.1.5
   NetBiosName : sql2016.base.local
   IsPingable : True
   PSRemotingAccessible : True
   DomainName : base.local
   LocalWindows : 10.0.15063.0
   LocalPowerShell : 5.1.15063.502
   LocalCLR : 4.0.30319.42000
   LocalSMOVersion : 13.0.0.0
   LocalDomainUser : True
   LocalRunAsAdmin : False
 
  .NOTES
   Tags: CIM, Test, Connection
   Author: Chrissy LeMaire
 
   Website: https://dbatools.io
   Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
   License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstance[]]$SqlInstance,
        [PSCredential]$Credential,
        [PSCredential]$SqlCredential,
        [switch]$Silent
    )
    process {
        foreach ($instance in $SqlInstance) {
            # Get local enviornment
            Write-Message -Level Verbose -Message "Getting local enivornment information"
            $localInfo = [pscustomobject]@{
                Windows  = [environment]::OSVersion.Version.ToString()
                PowerShell = $PSVersionTable.PSversion.ToString()
                CLR         = $PSVersionTable.CLRVersion.ToString()
                SMO         = ((([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.Fullname -like "Microsoft.SqlServer.SMO,*" }).FullName -Split ", ")[1]).TrimStart("Version=")
                DomainUser = $env:computername -ne $env:USERDOMAIN
                RunAsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
            }
            
            try {
                    <# gather following properties #>
                    <#
      InputName :
      ComputerName :
      IPAddress :
      DNSHostName :
      DNSDomain :
      Domain :
      DNSHostEntry :
      FQDN :
      FullComputerName :
      #>

                $resolved = Resolve-DbaNetworkName -ComputerName $instance.ComputerName -Credential $Credential
            }
            catch {
                Stop-Function -Message "Unable to resolve server information" -Category ConnectionError -Target $instance -ErrorRecord $_ -Continue
            }
            
            # Test for WinRM #Test-WinRM neh
            Write-Message -Level Verbose -Message "Checking remote acccess"
            try {
                $null = Invoke-Command2 -ComputerName $instance.ComputerName -Credential $Credential -ScriptBlock { Get-ChildItem } -ErrorAction Stop
                $remoting = $true
            }
            catch {
                $remoting = $_
            }
        
            # Test Connection first using Test-Connection which requires ICMP access then failback to tcp if pings are blocked
            Write-Message -Level Verbose -Message "Testing ping to $($instance.ComputerName)"
            $pingable = Test-Connection -ComputerName $instance.ComputerName -Count 1 -Quiet
            
            # SQL Server connection
            if ($instance.InstanceName -ne "MSSQLSERVER") {
                $sqlport = "N/A"
            }
            else {
            Write-Message -Level Verbose -Message "Testing raw socket connection to default SQL port"
                $tcp = New-Object System.Net.Sockets.TcpClient
                try {
                    $tcp.Connect($baseaddress, 1433)
                    $tcp.Close()
                    $tcp.Dispose()
                    $sqlport = $true
                }
                catch {
                    $sqlport = $false
                }
            }
            
            try {
                $server = Connect-SqlInstance -SqlInstance $instance.FullSmoName -SqlCredential $SqlCredential
                $connectSuccess = $true
            }
            catch {
                $connectSuccess = $false
                Stop-Function -Message "Issue connection to SQL Server on $instance" -Category ConnectionError -Target $instance -ErrorRecord $_ -Continue
            }
            
            $username = $server.ConnectionContext.TrueLogin
            if ($username -like "*\*") {
                $authType = "Windows Authentication"
            }
            else {
                $authType = "SQL Authentication"
            }
            
            # TCP Port
            try {
                $tcpport = (Get-DbaTcpPort -SqlInstance $server -Silent).Port
            }
            catch {
                $tcpport = $_
            }
            
            # Auth Scheme
            try {
                $authscheme = (Test-DbaConnectionAuthScheme -SqlInstance $server -WarningVariable authwarning -WarningAction SilentlyContinue).AuthScheme
            }
            catch {
                $authscheme = $_
            }
            
            if ($authwarning) {
                $authscheme = "N/A"
            }
            
            [pscustomobject]@{
                ComputerName   = $resolved.ComputerName
                InstanceName   = $instance.InstanceName
                SqlInstance        = $instance.FullSmoName
                SqlVersion = $server.Version
                ConnectingAsUser = $username
                ConnectSuccess  = $connectSuccess
                AuthType        = $authType
                AuthScheme        = $authscheme
                TcpPort            = $tcpport
                IPAddress       = $resolved.IPAddress
                NetBiosName    = $resolved.FullComputerName
                IsPingable       = $pingable
                PSRemotingAccessible = $remoting
                DomainName       = $resolved.Domain
                LocalWindows   = $localInfo.Windows
                LocalPowerShell = $localInfo.PowerShell
                LocalCLR       = $localInfo.CLR
                LocalSMOVersion = $localInfo.SMO
                LocalDomainUser = $localInfo.DomainUser
                LocalRunAsAdmin = $localInfo.RunAsAdmin
            }            
        }
    }
    end {
        Test-DbaDeprecation -DeprecatedOn "1.0.0" -Silent:$false -Alias Test-SqlConnection
    }
}