internal/Test-SqlLoginAccess.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
Function Test-SqlLoginAccess
{
<#
.SYNOPSIS
Internal function. Ensures login has access on SQL Server.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [Alias("ServerInstance", "SqlServer")]
        [object]$SqlInstance,
        [PSCredential]$SqlCredential,
        [string]$Login
        #[switch]$Detailed - can return if its a login or just has access
    )
    
    if ($SqlInstance.GetType() -ne [Microsoft.SqlServer.Management.Smo.Server])
    {
        $SqlInstance = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    }
    
    if (($SqlInstance.Logins.Name) -notcontains $Login)
    {
        try
        {
            $rows = $SqlInstance.ConnectionContext.ExecuteScalar("EXEC xp_logininfo '$Login'")
            
            if (($rows | Measure-Object).Count -eq 0)
            {
                return $false
            }
        }
        catch
        {
            return $false
        }
    }
    
    return $true
}