Dropping Users from SQL Server Database via Powershell

末鹿安然 提交于 2021-01-28 08:31:13

问题


I am trying to drop users from a SQL server database via PowerShell using the following code:

$sql_server = "mysqlserver"
$dbname = "mydb"

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null

$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server")($sql_server)
$db = $server.Databases["$dbname"]
$logins = $db.users

if ($logins.count -gt 0) {
    foreach ($login in $logins) {
        if ($login -notmatch "\[dbo\]|\[guest\]|\[INFORMATION_SCHEMA\]|\[sys\]") {
            $user = $login -replace '[^a-zA-Z\.\\]'
            write-host "Dropping $user"
            $db.Users[$user].Drop();
        }
    }
}

However I am getting an error stating:

Collection was modified; enumeration operation may not execute. + foreach ($login in $logins) { + ~~~~~~ + CategoryInfo : OperationStopped: (:) [], InvalidOperationException + FullyQualifiedErrorId : System.InvalidOperationException

I think its saying that $logins is being changed because I'm deleting users? I'm not sure how to work around that though?


EDIT


The following should work. Thanks to @Neil Hibbert for the help.

$sql_server = "mysqlserver"
$dbname = "mydb"

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null

$server = New-Object ("Microsoft.SqlServer.Management.Smo.Server")($sql_server)
$db = $server.Databases["$dbname"]
$logins = $db.users

if ($logins.count -gt 0) {
    for ($i=0; $i -lt $logins.count; $i++) {
        if ($logins[$i] -notmatch "\[dbo\]|\[guest\]|\[INFORMATION_SCHEMA\]|\[sys\]") {
            $user = $logins[$i] -replace '[^a-zA-Z\.\\]'
            write-host "Dropping $user"
            $db.Users[$user].Drop()
        }
    }
}

回答1:


I'm pretty certain the error message you are/were seeing is because you had set $logins to the list of $db.users and then tried to delete a user during the foreach loop.

Initializing $logins with $server.Logins (rather than $db.users) and then checking $db.Users.Contains($login) before calling $db.Users[$login].Drop() in your loop will fix your issue...



来源:https://stackoverflow.com/questions/44567793/dropping-users-from-sql-server-database-via-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!