我希望使用PowerShell检查SQL Server中是否存在用户,如果他们这样做,则删除他们的sa权限。到目前为止我已经
了clear
sqlps
cd "sql\$env:COMPUTERNAME\default"
Invoke-Sqlcmd -Query {if exists (select name from sys.database_principals where name='Builtin\Administrators') ALTER SERVER ROLE [sysadmin] DROP MEMBER [Builtin\Administrators]
else
print 'Account Does not exist or SA has already been removed from account' } #Runs a query on SQL Server to remove the SA privilege from Builtin\Administrators
exit
由于某些原因,当我尝试运行它时它会窒息。它抱怨以下错误:
Missing '(' after 'if' in if statement.
At line:4 char:26
Missing closing ')' after expression in 'if' statement.
At line:5 char:1
Missing statement block after if ( condition ).
At line:5 char:1
Missing statement block after 'else' keyword.
At line:6 char:1
将整个查询作为带单引号的字符串传递
clear
sqlps
cd "sql\$env:COMPUTERNAME\default"
Invoke-Sqlcmd -Query 'if exists (select name from sys.database_principals where name='Builtin\Administrators') ALTER SERVER ROLE [sysadmin] DROP MEMBER [Builtin\Administrators]
else
print 'Account Does not exist or SA has already been removed from account';' #Runs a query on SQL Server to remove the SA privilege from Builtin\Administrators
exit
至少给了我一个不同的错误。
Invoke-Sqlcmd : A positional parameter cannot be found that accepts argument 'Builtin\Administrators) ALTER SERVER ROLE [sysadmin] DROP MEMBER [Builtin\Administrators]
else
print Account'.
At line:4 char:14
+ Invoke-Sqlcmd <<<< -Query 'if exists (select name from sys.database_principals where name='Builtin\Administrators') ALTER SERVER ROLE [sysadmin] DROP MEMBER [Builtin\Administrators]
+ CategoryInfo : InvalidArgument: (:) [Invoke-Sqlcmd], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand
答案 0 :(得分:0)
invoke-sqlcmd的-Query参数是一个字符串。你传了一个脚本块。
这应该让你朝着正确的方向前进。
另外,@ Remus是对的...包括错误信息将为您提供更好的帮助。
编辑:既然您正在使用字符串参数,那么您应该在查询周围使用双引号,因为您在其中嵌入了单引号。