微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Powershell

太久没写了,罪过罪过!

嗯,今天无聊发现自己对sqlserver实在是一知半解,于是乎就把sqlserver浅浅地研究了一下。powershell一直不知道是啥,问了度娘,原来顾名思义就是个shell,而且是支持.net,但是之前实在没了解过。转载个吧。

 PowerShell早在sql Server 2005里就已经被集成了,而我第一次用却在sql Server 2008中。今天有空总结几个实际例子出来。欢迎这方面专家来完善一下:

  一、先不用sqlServerCmdletSnapin100这个SnapIn来写几个操作常用数据的脚本

  1. 由于有读者问如何用PowerShell显示数据库中表,以下是一个简单函数供参考

@H_502_251@

  2. 显示SQL查询出来的数据

双击代码全选
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#==============================================
 
# sql Server 2008 - PowerShell
 
 
# < c >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]
 
}
23
# 显示查询数据内容
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. 构建数据库联接字符串

33
###################################################################################################
# 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. 另一种风格的获取数据库数据

41
42
43
44
45
#================================================
# 类似DataTable GetDataTable(String strsql)
author >周利华</ >
#================================================
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
   
   
    #返回数据库
 
    return $DataSet.Tables[0]
 
  二、以上是普通PowerShell通过ADO.NET操作数据库,下面列出更酷的sql Server集成的PowerShell命令

  先看一下Invoke-sqlcmd这个关键的cmdlet的帮助信息:

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
@H_955_502@ 81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@H_502_251@

  仔细读完这个帮助,发现,上面所有对.NET Framework中ADO.NET的操作全可以用Invoke-sqlcmd代替,非常简洁方便。

  比如,获取home数据中所有用户表:

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 "MyComputerMyInstance"
   
   
    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:MyFolderTestsqlCmd.sql" | Out-File -filePath "C:MyFolderTestsqlCmd.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:sqlMyComputerMyInstance
 
    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:sqlMyComputerDEFAULTDatabasesAdventureWorks
 
    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
1 @H_502_251@

  比如,显示home数据库中userinfo表内容

Invoke-sqlcmd -Query "use home;SELECT name as tablename from sysobjects where xtype='U'" -QueryTimeout 3 | ft -auto   
1 @H_502_251@

  

  最后,补充,如果直接用sql Server 2008的Management Studio进去打开PowerShell,便可以直接操作类似Invoke-sqlcmd的cmdlets,但是如果没有Management Studio怎么办呢?

  很简单,用Add-PSSnapin sqlServerCmdletSnapin100轻松搞定。


咳咳。。。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐


Invoke-sqlcmd -Query "use home;SELECT * from UserInfo" -QueryTimeout 3 | ft -auto