如何使用PowerShell Runbook从Azure查询SQL Server(内部)?

时间:2019-04-01 13:43:04

标签: powershell sql-server-2016 azure-runbook

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

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

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

代码:

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的连接   服务器)

     

在第30行:char:5
  + Invoke-Sqlcmd-查询“选择1” -ServerInstance“服务器名”
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
  + CategoryInfo:InvalidOperation:(:) [Invoke-Sqlcmd],SqlException
  + FullyQualifiedErrorId:SqlExceptionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

0 个答案:

没有答案