Powershell连接字符串中的MSSQl'GO'处理

时间:2019-04-08 09:30:35

标签: sql-server powershell

我有一个用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。因此,如何在不为每个数据库创建多个连接的情况下仍在所有用户数据库中迭代和运行查询?

1 个答案:

答案 0 :(得分:2)

在连接上调用ChangeDatabase是切换数据库的另一种方法。

您可以按原样执行sp_change_users_login。不需要GO