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", "SqlInstance")]
[object]$SqlServer,
[System.Management.Automation.PSCredential]$SqlCredential,
[string]$Login
#[switch]$Detailed - can return if its a login or just has access
)

if ($SqlServer.GetType() -ne [Microsoft.SqlServer.Management.Smo.Server])
{
$SqlServer = Connect-SqlServer -SqlServer $SqlServer -SqlCredential $SqlCredential
}

if (($SqlServer.Logins.Name) -notcontains $Login)
{
try
{
$rows = $SqlServer.ConnectionContext.ExecuteScalar("EXEC xp_logininfo '$Login'")

if (($rows | Measure-Object).Count -eq 0)
{
return $false
}
}
catch
{
return $false
}
}

return $true
}