我有一个用Go
修补的sql查询,用于检查mssql中的孤立对象。
use DBName
go
sp_change_users_login 'report'
现在,我正在Powershell中为所有用户数据库自动化上述操作,并尝试获取孤立用户。
这是代码:
if($port)
{
$connectionString ="server=$servername,$port;Integrated Security=true;" #uid=$DBUserName; pwd=$dbpwd;Database=$DB;
}
else
{
$connectionString ="server=$servername;Integrated Security=true;"
}
$connection = New-Object System.Data.SqlClient.SqlConnection -ea Stop
$connection.ConnectionString=$connectionString
$connection.Open()
$db_query = @"
Select name from sys.sysdatabases where dbid > 4 and name not in ('ReportServer')
"@
$command = $connection.CreateCommand()
$command.CommandText = $db_query
$result = $command.ExecuteReader()
$object= New-Object System.Data.DataTable
$object.Load($result)
[System.Array]$DBs = $object.name
if($DBs -is [System.Array])
{
foreach($DB in $DBs)
{
## PROBLEM IS HERE ###
$orphan_users_query = @"
use $DB
GO
sp_change_users_login 'report'
"@
$command = $connection.CreateCommand()
$command.CommandText = $orphan_users_query
$result = $command.ExecuteReader()
$object= New-Object System.Data.DataTable
$object.Load($result)
$object | Out-File C:\temp\outfile_property.txt -Append -Force
}
}
问题是PS无法识别go
分隔符,因为它专用于MSSQL / SSMS。因此,如何在不为每个数据库创建多个连接的情况下仍在所有用户数据库中迭代和运行查询?