【问题标题】:Sql query in Powershell scheduled job fails to runPowershell计划作业中的Sql查询无法运行
【发布时间】:2013-06-19 22:25:27
【问题描述】:

您好,感谢您的关注! 我是 PS 和 SQL 的新手,但学到了很多东西。

环境:客户端:win7 64bit,服务器sql2008r2 on server2008r2 sp1,powershell3.0, 活动目录

我想做的事:每周从客户那里运行一次查询并通过电子邮件发送结果。

我可以在控制台中手动运行 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 来安排作业,但似乎找不到任何有我特定问题的人。

想法? 任何帮助将不胜感激:)

【问题讨论】:

    标签: sql powershell


    【解决方案1】:

    我相信是因为这行:

    $SqlQuery = gc sqlquery.sql
    

    假设您正在执行这样的计划任务:

    powershell.exe -file "C:\dir\myscript.ps1"
    

    当您将 powershell 脚本作为计划作业运行时,它会在 "C:\Windows\system32" 文件夹中启动。

    注意:当您指定“开始于”目录时也会发生这种情况

    因此,当您的 Get-Content 执行时,它会在以下位置查找您的 SQL 查询:"C:\Windows\system32\sqlquery.sql"

    每当我在需要访问任何文件的计划任务中运行脚本时,我总是对所有内容使用完整路径名,因为您无法假设事情是从哪里开始或执行的。

    【讨论】:

    • 啊哈!就是这样。万分感谢。现在我还有其他几项计划工作,我一直在考虑做......
    猜你喜欢
    • 2021-05-10
    • 2018-02-28
    • 2011-09-26
    • 1970-01-01
    • 2014-08-09
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多