使用PowerShell问题运行SQL命令

时间:2012-09-07 10:46:24

标签: sql powershell vbscript

我有以下使用VB脚本转换的powershell命令:

$conn = New-Object System.Data.SqlClient.SqlConnection(“Data Source=SERVER; Initial Catalog=DATABASE; Integrated Security=SSPI”) 
$conn.Open() 
$cmd1 = $conn.CreateCommand() 
$cmd1.CommandType = [System.Data.CommandType]::Text 
$cmd1.CommandText =“SELECT guid, name, [Serial Number] FROM dbo.wrksta as a inner join Inv_AeX_HW_Serial_Number as b on a.GUID=b._resourceGUID ORDER BY Name” 
$data = $cmd1.ExecuteReader() 
$cmd2 = $conn.CreateCommand() 
$cmd2.CommandType = [System.Data.CommandType]::Text 
$cmd2.CommandText =“SELECT top 1 [User] FROM dbo.Evt_aex_client_logon WHERE _resourceGuid = (SELECT top 1 Guid FROM dbo.Wrksta WHERE Name='" + $data["name"] + "' ORDER BY WrkstaID DESC) AND Event = 'logon' AND _eventTime > getdate()-60 GROUP BY [User] ORDER BY count([User]) desc” 
$data2 = $cmd2.ExecuteReader() 
$dt = new-object “System.Data.DataTable” 
$dt.Load($data2) 
$dt | format-table 
$conn.Close() 

如果查看第二个select语句,我想使用第一个变量$ data中的值,但我不确定如何编写它。在VB中它就像这个WHERE Name ='“+ workstation(”name“)。value +”'是以下在powershell中写这个的正确方法吗? '“+ $ data [”name“] +”'。我在$ date变量

中存储的名称列的值之后

以前执行此操作的VB低于

connString = "Provider=sqloledb;Data Source=SERVER;Initial Catalog=DATABASE;Integrated Security=SSPI;"
objSQL.Open connString 

sqlWorkstations = "SELECT guid, name, [Serial Number] FROM dbo.wrksta as a inner join Inv_AeX_HW_Serial_Number as b on a.GUID=b._resourceGUID ORDER BY Name"
Set workstation = objSQL.Execute(sqlWorkstations)

Do Until (workstation.EOF)

sqlUser = "SELECT top 1 [User] FROM dbo.Evt_aex_client_logon WHERE _resourceGuid = (SELECT top 1 Guid FROM dbo.Wrksta WHERE Name='" + workstation("name").value + "' ORDER BY WrkstaID DESC) AND Event = 'logon' AND _eventTime > getdate()-60 GROUP BY [User] ORDER BY count([User]) desc"
set user = objSQL.Execute(sqlUser)

if not user.eof then
  userName = user("User").value
else
  username = "??????"
end if

2 个答案:

答案 0 :(得分:2)

让自己更轻松,并加载SqlServerCmdletSnapin100管理单元。如果您正在处理SQL Server,它会为您处理大部分样板,并将查询运行到单个cmdlet。

上面的代码假定第一个查询只返回一行。这可能是也可能并非总是如此;我不知道你的数据库。如果它返回多个记录,那么您的代码将只提供与第一个查询中的第一个记录相对应的数据。

使用SqlServerCmdletSnapin100的{​​{1}}并处理返回多条记录的情况,请执行以下操作:

Invoke-SQLCmd

您也可以使用一个正确编写的查询检索所有数据,但又不知道难以说明的数据。您真的应该咨询您的DBA有关这些查询,以确保它们正确编写并正确匹配您的要求。

答案 1 :(得分:0)

ExecuteReader仅创建阅读器,但您需要调用$ data.Read()来检索第一条记录。 (参见链接的MSDN中的示例)