functions/Test-DbaCmConnection.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
function Test-DbaCmConnection
{
    <#
        .SYNOPSIS
            Tests over which paths a computer can be managed.
         
        .DESCRIPTION
            Tests over which paths a computer can be managed.
             
            This function tries out the connectivity for:
            - Cim over WinRM
            - Cim over DCOM
            - Wmi
            - PowerShellRemoting
            Results will be written to the connectivity cache and will cause Get-DbaCmObject and Invoke-DbaCmMethod to connect using the way most likely to succeed.
            This way, it is likely the other commands will take less time to execute. These other's too cache their results, in order to dynamically update connection statistics.
             
            This function ignores global configuration settings limiting which protocols may be used.
         
        .PARAMETER ComputerName
            The computer to test against.
         
        .PARAMETER Credential
            The credentials to use when running the test.
            Bad credentials are automatically cached as non-working, a behavior that can be disabled by the 'Cache.Management.Disable.BadCredentialList' configuration.
         
        .PARAMETER Type
            The connection protocol types to test.
            By default, all types are tested.
            Note that this function will ignore global configurations limiting the types of connections available and test all connections specified here instead.
             
            Available connection protocol types:
            "CimRM", "CimDCOM", "Wmi", "PowerShellRemoting"
         
        .PARAMETER Force
            Overrides safeguards and "do you really want to do this" kinds of issues.
            - Will force a test to proceed on a known bad credential
         
        .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
            PS C:\> Test-DbaCmConnection -ComputerName sql2014
         
            Performs a full-spectrum connection test against the computer sql2014.
            The results will be reported and registered, future calls from Get-DbaCmObject will thus recognize the results and optimize the query.
         
        .EXAMPLE
            PS C:\> Test-DbaCmConnection -ComputerName sql2014 -Credential $null -Type CimDCOM, CimRM
         
            This test will run a connectivity test against the computer sql2014
            - It will use windows authentication of the current user
            - It will only test Cim over DCOM and Cim over WinRM
         
            The results will be reported and registered, future calls from Get-DbaCObject will thus recognize the results and optimize the query.
         
        .EXAMPLE
            PS C:\> Test-DbaCmConnection -ComputerName sql2014 -Credential $cred -ClearCache
         
            Performs a full-spectrum connection test against the computer sql2014 using the credentials stored in $cred.
            Before doing so it will discard all previous results and settings.
            The results will be reported and registered, future calls from Get-DbaWmObject will thus recognize the results and optimize the query.
         
        .NOTES
            This function should not be called from within dbatools. It is meant as a tool for users only.
    #>

    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline = $true)]
        [Sqlcollective.Dbatools.Parameter.DbaCmConnectionParameter[]]
        $ComputerName = $env:COMPUTERNAME,
        
        [System.Management.Automation.PSCredential]
        $Credential,
        
        [sqlcollective.dbatools.Connection.ManagementConnectionType[]]
        $Type = @("CimRM", "CimDCOM", "Wmi", "PowerShellRemoting"),
        
        [switch]
        $Force,
        
        [sqlcollective.dbatools.Connection.ManagementConnectionType[]]
        $DisableConnectionType,
        
        [switch]
        $Silent
    )
    
    Begin
    {
        #region Configuration Values
        $disable_cache = Get-DbaConfigValue -Name "ComputerManagement.Cache.Disable.All" -Fallback $false
        $disable_badcredentialcache = Get-DbaConfigValue -Name "ComputerManagement.Cache.Disable.BadCredentialList" -Fallback $false
        #endregion Configuration Values
        
        #region Helper Functions
        function Test-ConnectionCimRM
        {
            [CmdletBinding()]
            Param (
                [Sqlcollective.Dbatools.Parameter.DbaCmConnectionParameter]
                $ComputerName,
                
                [System.Management.Automation.PSCredential]
                $Credential
            )
            
            try
            {
                $os = $ComputerName.Connection.GetCimRMInstance($Credential, "Win32_OperatingSystem", "root\cimv2")
                
                New-Object PSObject -Property @{
                    Success = "Success"
                    Timestamp = Get-Date
                    Authenticated = $true
                }
            }
            catch
            {
                if ($_.FullyQualifiedErrorId -eq "UnauthorizedAccessException")
                {
                    New-Object PSObject -Property @{
                        Success = "Error"
                        Timestamp = Get-Date
                        Authenticated = $false
                    }
                }
                else
                {
                    New-Object PSObject -Property @{
                        Success = "Error"
                        Timestamp = Get-Date
                        Authenticated = $true
                    }
                }
            }
        }
        
        function Test-ConnectionCimDCOM
        {
            [CmdletBinding()]
            Param (
                [Sqlcollective.Dbatools.Parameter.DbaCmConnectionParameter]
                $ComputerName,
                
                [System.Management.Automation.PSCredential]
                $Credential
            )
            
            try
            {
                $os = $ComputerName.Connection.GetCimDComInstance($Credential, "Win32_OperatingSystem", "root\cimv2")
                
                New-Object PSObject -Property @{
                    Success = "Success"
                    Timestamp = Get-Date
                    Authenticated = $true
                }
            }
            catch
            {
                if ($_.FullyQualifiedErrorId -eq "UnauthorizedAccessException")
                {
                    New-Object PSObject -Property @{
                        Success = "Error"
                        Timestamp = Get-Date
                        Authenticated = $false
                    }
                }
                else
                {
                    New-Object PSObject -Property @{
                        Success = "Error"
                        Timestamp = Get-Date
                        Authenticated = $true
                    }
                }
            }
        }
        
        function Test-ConnectionWmi
        {
            [CmdletBinding()]
            Param (
                [string]
                $ComputerName,
                
                [System.Management.Automation.PSCredential]
                $Credential
            )
            
            try
            {
                $os = Get-WmiObject -ComputerName $ComputerName -Credential $Credential -Class Win32_OperatingSystem -ErrorAction Stop
                New-Object PSObject -Property @{
                    Success = "Success"
                    Timestamp = Get-Date
                    Authenticated = $true
                }
            }
            catch [System.UnauthorizedAccessException]
            {
                New-Object PSObject -Property @{
                    Success = "Error"
                    Timestamp = Get-Date
                    Authenticated = $false
                }
            }
            catch
            {
                New-Object PSObject -Property @{
                    Success = "Error"
                    Timestamp = Get-Date
                    Authenticated = $true
                }
            }
        }
        
        function Test-ConnectionPowerShellRemoting
        {
            [CmdletBinding()]
            Param (
                [string]
                $ComputerName,
                
                [System.Management.Automation.PSCredential]
                $Credential
            )
            
            try
            {
                $parameters = @{
                    ScriptBlock = { Get-WmiObject -Class Win32_OperatingSystem -ErrorAction Stop }
                    ComputerName = $ComputerName
                    ErrorAction = 'Stop'
                }
                if ($Credential) { $parameters["Credential"] = $Credential }
                $os = Invoke-Command @parameters
                
                New-Object PSObject -Property @{
                    Success = "Success"
                    Timestamp = Get-Date
                    Authenticated = $true
                }
            }
            catch
            {
                # Will always consider authenticated, since any call with credentials to a server that doesn't exist will also carry invalid credentials error.
                # There simply is no way to differentiate between actual authentication errors and server not reached
                New-Object PSObject -Property @{
                    Success = "Error"
                    Timestamp = Get-Date
                    Authenticated = $true
                }
            }
        }
        #endregion Helper Functions
    }
    Process
    {
        foreach ($ConnectionObject in $ComputerName)
        {
            if (-not $ConnectionObject.Success) { Stop-Function -Message "Failed to interpret input: $($ConnectionObject.Input)" -Category InvalidArgument -Target $ConnectionObject.Input -Continue}
            
            $Computer = $ConnectionObject.Connection.ComputerName.ToLower()
            Write-Message -Level VeryVerbose -Message "[$Computer] Testing management connection"
            
            #region Setup connection object
            $con = $ConnectionObject.Connection
            #endregion Setup connection object
            
            #region Handle credentials
            $BadCredentialsFound = $false
            if ($con.DisableBadCredentialCache) { $con.KnownBadCredentials.Clear() }
            elseif ($con.IsBadCredential($Credential) -and (-not $Force))
            {
                Stop-Function -Message "[$Computer] The credentials supplied are on the list of known bad credentials, skipping. Use -Force to override this." -Continue -Category InvalidArgument -Target $Computer
            }
            elseif ($con.IsBadCredential($Credential) -and $Force)
            {
                $con.RemoveBadCredential($Credential)
            }            
            #endregion Handle credentials
            
            #region Connectivity Tests
            :types foreach ($ConnectionType in $Type)
            {
                switch ($ConnectionType)
                {
                    #region CimRM
                    "CimRM"
                    {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using Cim over WinRM"
                        $res = Test-ConnectionCimRM -ComputerName $con -Credential $Credential
                        $con.LastCimRM = $res.Timestamp
                        $con.CimRM = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] Cim over WinRM Results | Success: $($res.Success), Authentication: $($res.Authenticated)"
                        
                        if (-not $res.Authenticated)
                        {
                            Write-Message -Level Important -Message "[$Computer] The credentials supplied proved to be invalid. Skipping further tests"
                            $con.AddBadCredential($Credential)
                            break types
                        }
                    }
                    #endregion CimRM
                    
                    #region CimDCOM
                    "CimDCOM"
                    {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using Cim over DCOM"
                        $res = Test-ConnectionCimDCOM -ComputerName $con -Credential $Credential
                        $con.LastCimDCOM = $res.Timestamp
                        $con.CimDCOM = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] Cim over DCOM Results | Success: $($res.Success), Authentication: $($res.Authenticated)"
                        
                        if (-not $res.Authenticated)
                        {
                            Write-Message -Level Important -Message "[$Computer] The credentials supplied proved to be invalid. Skipping further tests"
                            $con.AddBadCredential($Credential)
                            break types
                        }
                    }
                    #endregion CimDCOM
                    
                    #region Wmi
                    "Wmi"
                    {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using Wmi"
                        $res = Test-ConnectionWmi -ComputerName $Computer -Credential $Credential
                        $con.LastWmi = $res.Timestamp
                        $con.Wmi = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] Wmi Results | Success: $($res.Success), Authentication: $($res.Authenticated)"
                        
                        if (-not $res.Authenticated)
                        {
                            Write-Message -Level Important -Message "[$Computer] The credentials supplied proved to be invalid. Skipping further tests"
                            $con.AddBadCredential($Credential)
                            break types
                        }
                    }
                    #endregion Wmi
                    
                    #region PowerShell Remoting
                    "PowerShellRemoting"
                    {
                        Write-Message -Level Verbose -Message "[$Computer] Testing management access using PowerShell Remoting"
                        $res = Test-ConnectionPowerShellRemoting -ComputerName $Computer -Credential $Credential
                        $con.LastPowerShellRemoting = $res.Timestamp
                        $con.PowerShellRemoting = $res.Success
                        Write-Message -Level VeryVerbose -Message "[$Computer] PowerShell Remoting Results | Success: $($res.Success)"
                    }
                    #endregion PowerShell Remoting
                }
            }
            #endregion Connectivity Tests
            
            if (-not $disable_cache) { [sqlcollective.dbatools.Connection.ConnectionHost]::Connections[$Computer] = $con }
            $con
        }
    }
    End
    {
        
    }
}