您好,感谢您的关注!我是 PS 和 SQL 的新手,但学到了很多东西。
环境:客户端:win7 64bit,服务器sql2008r2 on server2008r2 sp1,powershell3.0,Active Directory
我想做的事:每周从客户端运行查询并通过电子邮件发送结果。
我可以在控制台中手动运行 powershell 脚本,它工作正常,但是当我将它设置为计划作业时,它会完成脚本,但里面的 sql 查询失败/不运行。这是脚本:
#Date
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('MMM-dd')
#Connection Strings
$Database = "database"
$Server = "server"
#SMTP Relay Server
$SMTPServer = "mail.server"
#Export File
$AttachmentPath = "path"
#Errorlog
$errorlog= "log path"
$SqlQuery = gc sqlquery.sql
# Connect to SQL and query data, extract data to SQL Adapter
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "server=$Server;database=$Database;integrated security=true;"
$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
$nRecs = $SqlAdapter.Fill($DataSet) 2>&1 |Tee-Object -File $errorlog
$nRecs | Out-Null
#Populate Hash Table
$objTable = $DataSet.Tables[0] 2>&1 |Tee-Object -File $errorlog
#Export Hash Table to CSV File
$objTable | Export-CSV $AttachmentPath 2>&1 |Tee-Object -File $errorlog
#Remove quotes from CSV file
(get-content $AttachmentPath) |
foreach-object {$_ -replace '"', ''} |
set-content $AttachmentPath
#Remove first line from CSV file
(get-content $AttachmentPath |
select -skip 1) |
set-content $AttachmentPath
#Send SMTP Message
$Mailer = new-object Net.Mail.SMTPclient($SMTPServer)
$From = "from"
$To = "to"
$Subject = "Some text " + $currentdate
$Body = "Some more text.`n" + (import-csv -path $AttachmentPath | out-string)
$Msg = new-object Net.Mail.MailMessage($From,$To,$Subject,$Body)
$Msg.IsBodyHTML = $False
$Attachment = new-object Net.Mail.Attachment($AttachmentPath)
$Msg.attachments.add($Attachment)
$Mailer.send($Msg)
exit
现在,我最初在 sql server 日志中收到登录错误,表明它正在尝试使用 NT AUTHORITY\ANONYMOUS USER 登录,并意识到计划的作业没有设置为保存我的密码。更改了它,现在它使用我的域凭据登录;sql server 日志中不再出现登录失败错误。
我已经看到很多问题(在论坛上)使用 powershell 来安排作业,但似乎找不到任何有我特定问题的人。
想法?任何帮助将不胜感激 :)