我已经有一个Powershell脚本执行sql查询并格式化结果并通过电子邮件将其发送到指定为脚本命令行arg的电子邮件地址。如果需要,它还会附加结果的CSV。
我正在尝试为powershell脚本构建一个web前端,而不是cmd行使用的粉丝。我在ASP网页上使用C#。从命令行运行脚本工作正常,但是当我从网页运行脚本时,我收到TSQL错误。我调试了脚本,知道它正在运行带有正确参数的脚本,但是当它遇到Invoke-SqlCmd命令行开关时失败。我没有在stackoverflow或谷歌的其他部分看到任何错误。 建议?
Unhandled Execution Error
[ParserException]
ManagedBatchParser.Parser.Parse() +170
Microsoft.SqlServer.Management.PowerShell.ExecutionProcessor.ExecuteTSql(String sqlCommand) +275
[CmdletInvocationException]
System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input) +485
System.Management.Automation.Runspaces.Pipeline.Invoke() +84
_Default.Button1_Click(Object sender, EventArgs e) +660
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +154
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
PowerShell脚本:
$serverName="server"
$dbName="perfmon"
$mailServer="exchange"
$mailUser="testUser"
$mailPass="pass"
$workingPath="D:\scripts"
$scriptFile=$workingPath + "\queryStats.sql"
$tmpSql=$workingPath + "\tmpSql.sql"
$timeout="600"
$mailPass=ConvertTo-SecureString $mailPass -AsPlainText -Force
$cred=New-Object System.Management.Automation.PSCredential($mailUser,$mailPass)
$fromEmail="perfmonDB@test"
$toEmail=$args[0]
$getCSV=$args[1]
#add SQL snap ins
Add-PSSnapin SqlServerProviderSnapin100
Add-PSSnapin SqlServerCmdletSnapin100
$sqlCommand= "Invoke-Sqlcmd -ServerInstance $serverName -Database $dbName -InputFile $tmpSql -QueryTimeout $timeout"
echo "$sqlCommand" >> $workingPath\log.txt
$results=Invoke-Expression $sqlCommand
$emailResults = $results | format-table| Out-String
$emailResults = $results | convertto-html -property MachineName, InstanceName, CounterName, Average, Minimum, Maximum| Out-String
if($getCSV -eq "Yes")
{
$csvResults = $results | Convertto-csv
$results | Export-Csv $workingPath\results.csv
Send-MailMessage -To ($toEmail) -Subject "Perfmon Query Results" –From ($fromEmail) -Body $emailResults -Credential $cred -SmtpServer ($mailServer) -BodyAsHtml -Attachments $workingPath\results.csv
}
else {
Send-MailMessage -To ($toEmail) -Subject "Perfmon Query Results" –From ($fromEmail) -Body $emailResults -Credential $cred -SmtpServer ($mailServer) -BodyAsHtml
}
Remove-item $workingPath\tmpSql.sql
Remove-item $workingPath\results.csv