PowerShell早在SQL Server 2005里就已经被集成了, 而我第一次用却在SQL Server 2008中。今天有空总结几个实际例子出来。欢迎这方面专家来完善一下:
一、先不用SqlServerCmdletSnapin100这个SnapIn来写几个操作常用数据的脚本
1. 由于有读者问如何用PowerShell显示数据库中表,以下是一个简单函数供参考
This example reads a file containing Transact-SQL statements and sqlcmd commands, runs the file, and writes the output to another file. Ensure all output files are secured with the appropriate NTFS permissions.
Output sent to TestSqlCmd.rpt.
-------------- Example 3 --------------
C:\PS>$MyArray = "MYVAR1='String1'", "MYVAR2='String2'"
Invoke-Sqlcmd -Query "SELECT `$(MYVAR1) AS Var1, `$(MYVAR2) AS Var2;" -Variable $MyArray
This example uses an array of character strings as input to the -Variable parameter. The array defines multiple sqlcmd variables. The $ signs in the SELECT statement that identify the sqlcmd variables are escaped using the back-tick (`) character.
This example uses Set-Location to navigate to the SQL Server PowerShell provider path for an instance of the Database Engine. Then the example uses Get-Item to retrieve an SMO Server object for use as the -ServerInstance parameter of Invoke-Sqlcmd.
This example uses the PowerShell -Verbose parameter to return the message output of the PRINT command.
VERBOSE: abc
-------------- Example 6 --------------
C:\PS>Set-Location SQLSERVER:\SQL\MyComputer\DEFAULT\Databases\AdventureWorks
Invoke-Sqlcmd "SELECT DB_NAME() AS DatabaseName;"
This examples uses a positional string to supply the input to the -Query parameter. It also shows how Invoke-Sqlcmd uses the current path to set the database context to AdventureWorks.
WARNING: Using provider context. Server = MyComputer, Database = AdventureWorks.