我正在开展一项活动,我在server1中有一个表(t1),用于存储servername,userid和角色信息。
我创建了一个在server1上运行的PowerShell脚本,从表中收集这些信息,连接到远程服务器(servername)并将请求的角色授予用户ID。
请找到以下脚本:
$SQLServer = "Server1"
$SQLDatabase = "Db1"
$user = "select userid from T1"
$role = "select access from T1"
$server1 = "Select servername from T1"
<#store the table information in a text file for auditing#>
$Sqlquery = "Select servername,userid,access from T1"
$Test = Invoke-SQLCMD -Query $SqlQuery -serverinstance $SQLServer -Database
$SQLDatabase
$Test | format-list servername,userid,access| out-file "G:\EP\test.txt"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $Server1; Integrated Security =
True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$sqlSrv = New-Object 'Microsoft.SqlServer.Management.Smo.Server'
"SQLServer\Instance"
foreach ($login in $user)
{
$login.AddToRole($role)
}
$SqlConnection.Close()
运行上面的代码时,我看到以下错误:
方法调用失败,因为[System.String]不包含名为“AddToRole”的方法。
答案 0 :(得分:0)
$User
中的foreach ($login in $user)
定义在哪里?
它的null和foreach
迭代到null
(被驱逐的行为),$login
在这里变得一无所知。
您可能错过了$user
设置。