我用于执行 DMV 查询的辅助函数:
Function DMV_Query($DMV_Query) {
## Prepare the connection string based on information provided
$connectionString = "Provider=msolap;Data Source=$AS_Server;Initial Catalog=$CUBE;"
## Connect to the data source and open
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionString
$command = New-Object System.Data.OleDb.OleDbCommand
$command.Connection = $connection
$command.CommandText = $DMV_Query
$connection.Open()
## Fetch the results, and close the connection
$adapter = New-Object System.Data.OleDb.OleDbDataAdapter #$command
$adapter.SelectCommand = $command
$dataset = New-Object System.Data.DataSet
[void] $adapter.Fill($dataSet)
$connection.Close()
## Return all of the rows from their query
$dataSet.Tables[0]
}
示例调用:
$dmvResult = DMV_Query 'SELECT [SESSION_ID], [SESSION_SPID]
FROM $SYSTEM.DISCOVER_SESSIONS'
$dmvResult
存储在的内容示例$dmvResult
:
PS> $dmvResult | ConvertTo-Csv
"SESSION_ID","SESSION_SPID"
"D0kl8975r6df65","5567"
"fghu5r67f65","2234"
我想从$dmvResult
变量中选择所有列并将它们插入到 SQL 表中。这是我可以从变量中选择的方式吗?
# Doesn't work.
INSERT INTO [dbo].[Table]
SELECT * FROM @dmvResult