首页 > 解决方案 > 如何使用 PowerShell Runbook 从 Azure 查询 SQL Server(本地)?

问题描述

我需要从我们的 Azure 自动化帐户对本地 SQL Server 2016 实例执行查询,以便根据数据库中的内容发送电子邮件。

客户端无法建立会话,这是网络问题。我想我可能错过了一个中间步骤,或者没有为 SQL Server 模块提供足够的信息来定位我们的本地服务器。

  1. 我正在使用sqlserver模块
  2. 我已检查为本地实例启用了 TCP/IP 设置
  3. 我打开了 SQL Server Browser(我认为这不是必需的)
  4. 我在我的本地 Powershell ISE 上测试了代码并且它有效
  5. 我尝试使用 Windows Auth 和 SQL Server auth

代码:

Import-Module sqlserver

$from       = "x.y@dom.com"
$to         = "email@gmail.com"
$SMTPServer = "smtp.sendgrid.net"
$SMTPPort   = "587"
$username   = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
$password   = "xxxxxxxxxxx"

$subject    = "Email test from Azure SMTP server"
$body       = "Test email body, no content to see here!"

#$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
#$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
#$smtp.Send($From, $To, $subject, $body)



function Get-EmailBody{

}

<#
    Get all emails which have been merged into the emailChangeHistory table with the flag emailSent = 0.
#>
function Get-ChangeHistory($sqlServer, $database, $emailSent = 0){
    Invoke-Sqlcmd -Query "select 1" -ServerInstance "servername" 
}

Get-ChangeHistory -sqlServer $null, -database $null, -emailSent $null

我收到此错误:

Invoke-Sqlcmd:建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。
服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。(提供者:命名管道提供者,错误:40 - 无法打开与 SQL Server 的连接)

在 line:30 char:5
+ Invoke-Sqlcmd -Query "select 1" -ServerInstance "servername"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Invoke-Sqlcmd] , SqlException
+ FullyQualifiedErrorId : SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

标签: powershellsql-server-2016azure-runbook

解决方案


推荐阅读