0

I already used Microsoft.SqlServer.Management.Smo.Login in Powershell to create SQL-login with no problem.

Just for the new SQL-login created, how could I use Powershell to set its permissions as image show below? (I want to set "View any database" to be "Deny").

Thanks heaps!

enter image description here

1
  • 1
    How about using TSQL? You'd find a lot more help for using GRANT and DENY statements instead of messing around with management objects. Commented Jan 9, 2014 at 8:11

2 Answers 2

1
#Valid serverpermissions:
#AdministerBulkOperations AlterAnyConnection AlterAnyCredential AlterAnyDatabase AlterAnyEndpoint AlterAnyEventNotification
#AlterAnyLinkedServer AlterAnyLogin AlterAnyServerAudit   AlterResources AlterServerState AlterSettings AlterTrace AuthenticateServer
#ConnectSql ControlServer CreateAnyDatabase CreateDdlEventNotification CreateEndpoint CreateTraceEventNotification ExternalAccessAssembly
#UnsafeAssembly ViewAnyDatabase ViewAnyDefinition ViewServerState 

    #Set variables
    $ServerInstance = ""
    $name = ""
    $action = ""

    $server = new-object ("Microsoft.SqlServer.Management.Smo.Server") $ServerInstance

        $perm = new-object ('Microsoft.SqlServer.Management.Smo.ServerPermissionSet')
        $perm.$($permission.ToString()) = $true

        switch ($action)
        { 
            'Grant'  { $server.Grant($perm,$name) }
            'Deny'   { $server.Deny($perm,$name) }
            'Revoke' { $server.Revoke($perm,$name) }
        }
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Chad, thanks a lot. It works. BTW, where could I find the document about these library?
The code about is based on the sqlpsx CodePlex project in Module\SqlServer\SqlServer.psm1. For in on SMO classes MSDN lists properties and methods, but can be tricky to find--for example how do you know server perms are server and not login method.
0

Assuming the SQL PowerShell module is loaded, I use this:

$Instance=Get-Item -Path "SQLSERVER:\SQL\$env:COMPUTERNAME\<instance name>"
$DBPermSet=[Microsoft.SqlServer.Management.Smo.ServerPermissionSet]::new()
$DBPermSet.Add([Microsoft.SqlServer.Management.Smo.ServerPermission]::ViewAnyDatabase)
$Instance.Deny($DBPermSet,"<user name>")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.