获取与数据库关联的用户

时间:2015-06-29 05:43:59

标签: powershell

我是power shell的新手,我在几篇博客中读到它主要用于自动化。我有一个要求,我需要为SQL生成审计报告,该报告应显示谁是特定数据库的用户。这将有助于我删除不再在我的组织中的人。

我需要的格式如下:

{{1}}

我已经浏览了几个博客,我能够连接远程服务器数据库,但我不知道如何提取用户。任何人都可以建议我是否可以使用power shell自动化此报告来提取报告。

如果您需要任何其他详细信息,请与我们联系。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

function SQL-Get-Logins
{
    <#
    .SYNOPSIS
    Returns a list of SQL Server logins defined on the specified server/instance.

    .DESCRIPTION
    This function returns a complete list of all logins defined for the specified
    server/instance, including the login type, the default database, and the server
    role.

    .PARAMETER server
    The computer hosting SQL Server.

    .PARAMETER instance
    The instance to be used on that server.

    .PARAMETER saPassword
    The 'sa' password on that server\instance

    .EXAMPLE
    SQL-Get-Logins myserver myinstance sa | %{ Write-Host $_.LoginName }
    #>

    param (
        [parameter(Mandatory = $true)][string] $server,
        [parameter(Mandatory = $false)][string] $instance  = 'MSSQL',
        [parameter(Mandatory = $true)][string] $saPassword
    )

    $logins = $null

    try
    {
        $query = @"
        select a.name as LoginName, a.type_desc as LoginType, a.default_database_name as DefaultDBName,
        case when b.sysadmin = 1 THEN 'sysadmin'
                  when b.securityadmin=1 THEN 'securityadmin'
                  when b.serveradmin=1 THEN 'serveradmin'
                  when b.setupadmin=1 THEN 'setupadmin'
                  when b.processadmin=1 THEN 'processadmin'
                  when b.diskadmin=1 THEN 'diskadmin'
                  when b.dbcreator=1 THEN 'dbcreator'
                  when b.bulkadmin=1 THEN 'bulkadmin'
                  else 'Public' end as ServerRole
        from sys.server_principals a join master..syslogins b on a.sid=b.sid where a.type  <> 'R' and a.name not like '##%'
"@

        $sqlConnection = New-Object System.Data.SqlClient.SqlConnection
        $sqlConnection.ConnectionString = "Server=$server\$instance;Database=master;User Id=sa;Password=$saPassword;Trusted_Connection=False;"
        $adapter = New-Object System.Data.SqlClient.SqlDataAdapter ($query, $sqlConnection)
        $dataSet = New-Object System.Data.Dataset
        $adapter.Fill($dataSet) | Out-Null 

        $logins = $dataSet.Tables[0]

        foreach ($login in $logins)
        {
            $loginName = $login.ItemArray[0]
            $loginType = $login.ItemArray[1]
            $defaultDbName = $login.ItemArray[2]
            $serverRole = $login.ItemArray[3]

            Write-Output "$($MyInvocation.InvocationName): LoginName: $loginName, LoginType: $loginType, Default database: $defaultDbName, Server Role: $serverRole"
        }
    }

    catch
    {
        Write-Error "$($MyInvocation.InvocationName): $_"
    }

    return $logins
}