设为首页 收藏本站
查看: 1424|回复: 0

PowerShell在SQL Server 2008中一些用法 [实例]

[复制链接]

尚未签到

发表于 2015-6-30 15:37:20 | 显示全部楼层 |阅读模式
  PowerShell早在SQL Server 2005里就已经被集成了, 而我第一次用却在SQL Server 2008中。今天有空总结几个实际例子出来。欢迎这方面专家来完善一下:
  一、先不用SqlServerCmdletSnapin100这个SnapIn来写几个操作常用数据的脚本
  1. 由于有读者问如何用PowerShell显示数据库中表,以下是一个简单函数供参考

#==============================================
# SQL Server 2008 - PowerShell
# 显示用户表
# zivsoft
#==============================================
function ShowCustomizedDataTable{
    $SQLSERVER=read-host "Enter SQL Server Name:"
    $Database=read-host "Enter Database Name:"
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $CnnString = "Server=$SQLSERVER;Database=$DATABASE;Integrated Security=True"
    $SqlConnection.ConnectionString = $CnnString
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlCmd.CommandText = "select name from sysobjects where type='u'"
    $SqlCmd.Connection = $SqlConnection
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $SqlConnection.Close()
    $DataSet.Tables[0]
}  
  2. 显示SQL查询出来的数据

#==============================================
# SQL Server 2008 - PowerShell
# 显示查询数据内容
# zivsoft
#==============================================
function Get-DataTable([string]$query)
{
    $dataSet= new-object "System.Data.DataSet" "DataSetName"
    $da = new-object "System.Data.SqlClient.SqlDataAdapter" ($query, $CnnString)
    [void] $da.Fill($dataSet)
    return $dataSet.Tables[0]
}  
  3. 构建数据库联接字符串


###################################################################################################
# www.zivsoft.com
# 设置数据库连接字符串
###################################################################################################
function global:Set-SqlConnection( $Server = $(Read-Host "SQL Server Name"), $Database = $(Read-Host "Default Database"),  $UserName , $Password  )
{
    #如果用户名和密码都不为空
    if( ($UserName -gt $null) -and ($Password -gt $null)) {
        $login = "User Id = $UserName; Password = $Password"
    }
    else {
        #采用整合安全机制登陆
        $login = "Integrated Security = True"
    }
    #数据库连接字符串
    $SqlConnection.ConnectionString = "Server = $Server; Database = $Database; $login"
}  
  4. 另一种风格的获取数据库数据

#================================================
# 类似DataTable GetDataTable(String strSQL)
# 周利华
#================================================
function global:Get-SqlDataTable( $Query = $(Read-Host "输入SQL语句"))
{
    #打开数据库
    if (-not ($SqlConnection.State -like "Open")) { $SqlConnection.Open() }
   
    #实例化SQLCommand
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $Query, $SqlConnection
   
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    $SqlAdapter.SelectCommand = $SqlCmd
   
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet) | Out-Null
   
    $SqlConnection.Close()
   
    #返回数据库表
    return $DataSet.Tables[0]
}  
  二、以上是普通PowerShell通过ADO.NET操作数据库,下面列出更酷的SQL Server集成的PowerShell命令
  先看一下Invoke-Sqlcmd这个关键的cmdlet的帮助信息:


NAME
    Invoke-Sqlcmd
   
SYNOPSIS
    Runs a script containing statements from the languages (Transact-SQL and XQuery) and commands supported by the SQL Server sqlcmd utility.
   
    --------------  Example 1 --------------
   
    C:\PS>Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance"
   
   
    This example connects to a named instance of the Database Engine on a computer and runs a basic Transact-SQL script.
   
   
    TimeOfQuery
    -----------
    10/7/2007 1:04:20 PM
   
    --------------  Example 2 --------------
   
    C:\PS>Invoke-Sqlcmd -InputFile "C:\MyFolder\TestSqlCmd.sql" | Out-File -filePath "C:\MyFolder\TestSqlCmd.rpt"
   
   
    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.
   
   
    Var1                        Var2
    ----                        ----
    String1                     String2
   
    --------------  Example 4 --------------
   
    C:\PS>Set-Location SQLSERVER:\SQL\MyComputer\MyInstance
    Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance (Get-Item .)
   
   
    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.
   
   
    TimeOfQuery
    -----------
    10/18/2007 8:49:43 PM
   
    --------------  Example 5 --------------
   
    C:\PS>Invoke-Sqlcmd -Query "PRINT N'abc'" -Verbose
   
   
    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.
   
    DatabaseName
    ------------
    AdventureWorks
      
  仔细读完这个帮助,发现,上面所有对.NET Framework中ADO.NET的操作全可以用Invoke-Sqlcmd代替,非常简洁方便。
  比如,获取home数据中所有用户表:

Invoke-Sqlcmd -Query "use home;SELECT name as tablename from sysobjects where xtype='U'" -QueryTimeout 3 | ft -auto     
  比如,显示home数据库中userinfo表内容:

Invoke-Sqlcmd -Query "use home;SELECT * from UserInfo" -QueryTimeout 3 | ft -auto    DSC0000.jpg
  最后,补充,如果直接用SQL Server 2008的Management Studio进去打开PowerShell,便可以直接操作类似Invoke-Sqlcmd的cmdlets,但是如果没有Management Studio怎么办呢?
  很简单,用Add-PSSnapin SqlServerCmdletSnapin100轻松搞定。
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-82001-1-1.html 上篇帖子: shell脚本:猜数字游戏 下篇帖子: Exchange 2010 PowerShell
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表