通过PowerShell进行的SQL Server查询未返回预期结果

时间:2017-10-02 16:10:17

标签: sql powershell

我有一个PowerShell脚本,它正在查询我的本地SQL Server数据库。我知道它可以连接并与数据库通信,因为如果我将连接信息更改为错误,我的try / catch块会抛出预期的错误。我有一个名为MaintMode的表格,其中包含2列:SiteNameStatus

当我在SQL Server Management Studio中运行SELECT SiteName, Status FROM dbo.MaintMode时,我得到:

SiteName Status
MySite   off

这很棒。但是,当我让我的PowerShell脚本运行完全相同的查询时,它只返回1到控制台。如何让我的PowerShell脚本返回我在SQL Server Management Studio中看到的相同输出?

我的PowerShell代码如下:

# Set up connection to the SQL Server

$SQLServer = "localhost\SQLEXPRESS"
$SQLDBName = "MaintSiteDB"
$uid = "removed"
$pwd = "removed"

#Specify the query to run

$SqlQuery = "SELECT SiteName, Status FROM dbo.MaintMode;"

#Build connection to the SQL Server

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = 
$SQLDBName; Integrated Security = false; User ID = $uid; Password = $pwd;"

#Connect to the SQL Server and run the query

Try

{
  $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
  $SqlCmd.CommandText = $SqlQuery
  $SqlCmd.Connection = $SqlConnection
  $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
  $SqlAdapter.SelectCommand = $SqlCmd
  $DataSet = New-Object System.Data.DataSet
  $SqlAdapter.Fill($DataSet)
  $QueryResult = $SqlAdapter.Fill($DataSet)
}

catch
{
  Write-Output "Failed to connect to $SQLServer. Please check your 
connection parameters and try again."
  Break
}

0 个答案:

没有答案