sql - 使用Powershell的多个SQL选择查询

标签 sql powershell select multiple-select

搜索了很多,但是找不到解决我问题的方法。
首先,我有一个脚本,可以通过该脚本通过本地Veeam数据库进行一些查询。
它有一些选择查询,但是每次我运行它时,它只会给我第一个查询的结果,而不是其他查询的结果。我只是想让代码更瘦一点,所以也许有人可以给我小费
我只是得到$ job和$ space_backup的结果。我不想有四个不同的查询,但是如果不可能的话,我必须继续使用它。我将不胜感激任何帮助。

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$dbServer;Database=$db;uid=$User;password=$Pass;"
$SQLConnection.Open()
$SQLCommand = $SQLConnection.CreateCommand()
$SQLCommand.CommandText = 
"SELECT TOP 1 stored_size AS size, job_name AS job FROM [VeeamBackup].[dbo].[ReportSessionView] ORDER BY [creation_time] DESC;"
"SELECT [free_space] AS [free] FROM [VeeamBackup].[dbo].[BackupRepositories] WHERE (name != 'Default Backup Repository');"
"SELECT  SUM(backup_size) AS backupsize FROM [VeeamBackup].[dbo].[WmiServer.RestorePointsView];"
"SELECT TOP 1 reason AS Reason, stop_details AS Detail FROM [VeeamBackup].[dbo].[Backup.Model.JobSessions] ORDER BY creation_time DESC;"
$SQLReader = $SQLCommand.ExecuteReader()
foreach($SQLCommand in $SQLReader.Read()){
    $space_backup = $SQLReader["size"]
    $job = $SQLReader["job"]
    $space_free = $SQLReader["free"]
    $space_all = $SQLReader["backupsize"]
    $reason = $SQLReader["Reason"]
    $detail = $SQLReader["Detail"]
    $SQLReader.Close()
}

最佳答案

这应该为您工作。只需添加SqlDataAdapter和DataSet代替$ SQLReader = $ SQLCommand.ExecuteReader()命令,然后选择一个长字符串即可。我结束了我的每一个,同时用进行了测试; 。

$readAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$readSet = New-Object System.Data.DataSet
$readAdapter.SelectCommand = $SQLCommand
$readAdapter.Fill($readSet) |out-null
$SQLConnection.Close()
Foreach ($row in $readSet.Tables[0].rows) {
   Write-Output "Do what you want with the first query results here"
   Write-Output "$($row.size)  $($row.job)"
}
Foreach ($row in $readSet.Tables[1].rows) {
   Write-Output "Do what you want with the second query results here"
   Write-Output "$($row.free)  "
}
继续为每个查询添加一个Foreach

关于sql - 使用Powershell的多个SQL选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35152899/

相关文章:

php - 将 PHP 变量分配给 SQL 结果

sql - TSQL:在单个表中查找唯一条目

powershell - 取反 -switch(除了 switch 参数之外的所有参数)

javascript - .env 变量在 React JS 应用程序中返回未定义

mysql - 在 MySQL 中选择除一列之外的所有列?

mysql - 将列值映射到其包含行的日期

sql-server - 如果没有行匹配则返回一个值

php - 我的 php 不解释 postgresql 或 sql 函数

sql - 使用 2016 年之前的 tsql 功能解压缩 gzip 字段

powershell - PSExec 在 start-job 中运行时永远不会完成