英文:
PowerShell script to add domain user to multiple servers with results (success / failure)
问题
我是PowerShell新手,我在使用脚本时遇到了问题。
基本上,我已经创建了一个脚本,可以将sysadmin添加到列在文本文件中的多个SQL服务器中。文本文件只包含一个服务器名称的列。脚本似乎工作正常。
我想要生成一个报告,以指出它是否在列表中的任何服务器上失败。这可以是CSV或文本格式。我只是不想假定脚本在100多个服务器上都正常运行,后来才发现帐户或服务器存在问题。
这是我使用的脚本:
Import-Module -Name SqlPs
$servers = Get-Content -Path C:\Temp\servers.txt
$servers |
foreach{ `
Invoke-Sqlcmd -ServerInstance $_ `
-Database 'Master' `
-Query "EXEC master..sp_addsrvrolemember @loginame = N'DOMAIN\USERNAME', @rolename = N'sysadmin';" `
-QueryTimeout 10 `
}
任何帮助将不胜感激。
英文:
I am a PowerShell newbie and I am having trouble with a script.
Basically, I have created a script that will add a sysadmin to multiple SQL servers listed in a text file. The text file is just one column of server names. The script seems to work fine.
I would like to have a report stating if it failed on any of the servers in the list. This could be csv or text. I just don't want to assume the script ran fine on 100+ servers to only find out later that there were issues with the account or server.
This the script I am using:
Import-Module -Name SqlPs
$servers = Get-Content -Path C:\Temp\servers.txt
$servers |
foreach{ `
Invoke-Sqlcmd -ServerInstance $_ `
-Database 'Master' `
-Query "EXEC master..sp_addsrvrolemember @loginame = N'DOMAIN\USERNAME', @rolename = N'sysadmin';" `
-QueryTimeout 10 `
}
Any assistance would be greatly appreciated.
答案1
得分: 0
我建议将你的命令包装在一个try/catch块中,以汇总失败:
Import-Module -Name SqlPs
$errors = [System.Collections.Generic.List[string]]@()
$params = @{
Database = 'Master'
Query = "EXEC master..sp_addsrvrolemember @loginame = N'DOMAIN\USERNAME', @rolename = N'sysadmin';"
QueryTimeout = 10
ErrorAction = 'Stop'
}
foreach ($server in Get-Content -Path C:\Temp\servers.txt) {
try {
Invoke-Sqlcmd -ServerInstance $server @params
} catch {
$errors.Add("$server failed: $_")
}
}
$errors > errors.log
这里最重要的是 ErrorAction:Stop
,它会将你的命令转化为一个可被try/catch块捕获的_终止_错误。
英文:
I would suggest wrapping your command in a try/catch block to aggregate the failures:
Import-Module -Name SqlPs
$errors = [System.Collections.Generic.List[string]]@()
$params = @{
Database = 'Master'
Query = "EXEC master..sp_addsrvrolemember @loginame = N'DOMAIN\USERNAME', @rolename = N'sysadmin';"
QueryTimeout = 10
ErrorAction = 'Stop'
}
foreach ($server in Get-Content -Path C:\Temp\servers.txt) {
try {
Invoke-Sqlcmd -ServerInstance $server @params
} catch {
$errors.Add("$server failed: $_")
}
}
$errors > errors.log
The most important thing here is ErrorAction:Stop
which will turn your command into a terminating error to be caught by the try/catch block.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论