[英]Use an array to add permission to a list of users in ssms
I run several classrooms and lab environments.我经营着几个教室和实验室环境。 The students in one of the classes have to log into the interface and connect with my server, which then creates their account in SSMS.
其中一个班级的学生必须登录界面并连接到我的服务器,然后在 SSMS 中创建他们的帐户。 Then I have to go in and manually add the permissions they need to do what they need to do for class.
然后我必须在 go 中手动添加他们需要为 class 做他们需要做的事情的权限。 When my server "re-syncs" with the other online server, they lose their SSMS permissions.
当我的服务器与其他在线服务器“重新同步”时,它们会失去 SSMS 权限。 (I'm being purposefully vague, don't focus on why they lose perms. I'm not doing anything wrong).
(我故意含糊其辞,不要专注于他们为什么会失去烫发。我没有做错任何事)。
I can create the list of users and save it to an array.我可以创建用户列表并将其保存到数组中。 I know the ssms commands I need to run.
我知道我需要运行的 ssms 命令。 Where I'm drawing a blank is how do I get my PS1 into the SSMS command.
我在空白处是如何让我的 PS1 进入 SSMS 命令。 I'm fairly sure I need to do a foreach loop and save it to a.sql file and run that, but my google skills are failing me.
我相当确定我需要做一个 foreach 循环并将其保存到一个 .sql 文件并运行它,但我的谷歌技能让我失望了。 Any help would be appreciated, Also my first time posting on this website.
任何帮助将不胜感激,也是我第一次在这个网站上发帖。 so I'm sorry if this looks silly.
所以如果这看起来很傻,我很抱歉。
$Response = 'y'
$User = $Null
$UserList = @()
#Get a list of users#
Do
{
$User = Read-Host -Prompt 'Input user name'
$Response = Read-Host 'Would you like to add any
additional users? y/n'
if ($User -ne '') {$UserList += $User}
}
Until ($Response -eq 'n')
#Loop through the list of users and add to a sql file#
foreach ($User in $UserList) {
}
#The SQL command to add user perms in SQL#
#sqlcmd
#use <db>
#exec sp_addrolemember 'group1','$User'
#exec sp_addrolemember 'group2','$User'
#go
You could do something like the following to create file.sql
that you can run with Invoke-SqlCmd
or from TSQL.您可以执行以下操作来创建
file.sql
,您可以使用Invoke-SqlCmd
或 TSQL 运行该文件。
$template = { @"
exec sp_addrolemember 'group1','$user'
exec sp_addrolemember 'group2','$user'
"@
}
'use <db>' | Set-Content file.sql
$SqlCommands = foreach ($user in $userlist) {
& $template
}
$SqlCommands | Add-Content file.sql
'go' | Add-Content file.sql
Explanation:解释:
Using a script block ( {}
surrounding code), you can specify variables that are only evaluated when the script block is called.使用脚本块(
{}
周围的代码),您可以指定仅在调用脚本块时评估的变量。 You can simply call a script block in a child scope using &
operator.您可以使用
&
运算符简单地调用子 scope 中的脚本块。
@""@
denotes a here-string . @""@
表示here-string 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.