如何防止SQL代理Powershell作业在出错时停止
我有一个脚本,foreach通过一个JSON配置文件通过一堆不同的帐户ftp凭据。如果用户在第三方网站上更改FTP密码,我完全可以预料会出现“未找到文件”类型的错误,甚至有时会出现“错误,错误的密码” 脚本在自己运行时(通过调度器或通过ISE)会发现任何错误,将它们写入数据库并通过团队通知适当的人员,然后脚本继续并转到foreach循环中的下一个JSON对象 问题是,当我将其作为SQL代理powershell作业(或CMDExec)运行时,一个错误就会停止整个脚本。我所读到的关于这个的一切似乎都在说sql实际上应该继续脚本,但它只是不 如果其中一个JSON配置的“帐户”出现问题,我将尝试让脚本继续。以下是脚本:如何防止SQL代理Powershell作业在出错时停止,sql,sql-server,powershell,agent,sql-server-agent,Sql,Sql Server,Powershell,Agent,Sql Server Agent,我有一个脚本,foreach通过一个JSON配置文件通过一堆不同的帐户ftp凭据。如果用户在第三方网站上更改FTP密码,我完全可以预料会出现“未找到文件”类型的错误,甚至有时会出现“错误,错误的密码” 脚本在自己运行时(通过调度器或通过ISE)会发现任何错误,将它们写入数据库并通过团队通知适当的人员,然后脚本继续并转到foreach循环中的下一个JSON对象 问题是,当我将其作为SQL代理powershell作业(或CMDExec)运行时,一个错误就会停止整个脚本。我所读到的关于这个的一切似乎都
#region setup ================================== SETUP BLOCK ==================================#
#Email Recipients
$Receivers = @{
"teams channel" = "7e8bfd86.MYDOMAIN.com@amer.teams.ms"
}
#Logging
$LogSourceID = 50
$LogSourceMachineName = 'CAFeed_UO_DB02'
#JsonPull
$json = Get-Content -raw -encoding "UTF8" -path "D:\Data\feeds\CA\cfg\CAFeedConfig_migratetest.JSON" | convertfrom-json
$accounts = $json
#StaticVariables
$uo_path = 'D:\data\feeds\CA\uo\'
#VerboseLogging
Start-Transcript -path "D:\data\feeds\CA\scripts\uo_verboselog.txt" -Append
#endregion setup #================================== SETUP BLOCK ==================================#
foreach ($account in $accounts) #Enable This Line to Run through all accounts
#foreach ($account in $accounts | Where-Object {$_.account -eq "ACCOUNTNAME"}) #Enable This line to run through only specified Accounts
#This IF Statement tests to see if the update file exists, if it does not, a database log is written
{
if ((Test-Path -PathType Leaf $account.uo_sourcefile) -eq $false)
{write-host ($account.uo_sourcefile + "not detected")
#Assemble the Query
$sqlresult = "CA_UO File Not Detected:" + $account.uo_sourcefile
$sqlcontext = ("NoFile")
$starttime = (get-date).ToString()
$endtime = (get-date).ToString()
write-BelamiDBLog -resultRecord $sqlresult -contextRecord $sqlcontext -machineNameRecord $LogSourceMachineName -sourceID $logSourceID -starttime $starttime -endtime $endtime
}
else
{
#region ftp
$ErrorActionPreference = "Continue"
write-host $account.uo_ftpdest $account.account, $account.username, $account.password, $account.uo_sourcefile
# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create($account.uo_ftpdest)
$ftp = [System.Net.FtpWebRequest]$ftp
# build authentication and connection
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential($account.username,$account.password)
$ftp.UseBinary = $true
$ftp.UsePassive = $true
$ftp.timeout = -1
#start a timer and error handling
$starttime = (get-date).ToString()
write-host "starting at $starttime"
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes($account.uo_sourcefile)
$ftp.ContentLength = $content.Length
write-host ("File Size: " + ($content.Length / 1000000)+"MB" )
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
$rs.Close()
$rs.Dispose()
$endtime = (get-date).ToString()
write-host "done at $endtime"
$totaltime = NEW-TIMESPAN -Start $starttime -End $endtime
$xferrate = ($content.length / $totaltime.TotalSeconds / 1000000)
$xferrate = [math]::Round($xferrate,2)
write-host $xferrate "MB/Sec"
#endregion ftp
#region error handle
if ($error)
{
$sqlresult = ('CA_UO Transport Failed'+ $xferrate + 'MB/sec')
$sqlcontext = ($account.account + ' | ' + ($content.Length / 1000000) +'MB')
write-BelamiDBLog -resultRecord $sqlresult -contextRecord $sqlcontext -machineNameRecord $LogSourceMachineName -sourceID $logSourceID -starttime $starttime -endtime $endtime
$Parameters = @{
FromAddress = "CAFeedAlerts@MYDOMAIN.com"
ToAddress = "placeholder"
Subject = "CA_UO Failed"
Body = "CA_UO Failed with error $error"
Token = "REDACTED"
FromName = "CAFeed Alerts"
ToName = "placeholder"
}
Foreach ($Receiver in $Receivers.GetEnumerator()) {
$Parameters.ToName = $Receiver.name
$Parameters.ToAddress = $Receiver.value
Send-PSSendGridMail @Parameters
$error.Clear()
}
}
else
{
$sqlresult = ('CA_UO Transport Success '+ $xferrate + 'MB/sec')
$sqlcontext = ($account.account + ' | ' + ($content.Length / 1000000) +'MB')
write-BelamiDBLog -resultRecord $sqlresult -contextRecord $sqlcontext -machineNameRecord $LogSourceMachineName -sourceID $logSourceID -starttime $starttime -endtime $endtime
}
#ArchiveRemainingFile
$datestr = get-date -Format MMddhhmm
Compress-Archive -Path $account.uo_sourcefile -DestinationPath ('D:\data\feeds\CA\uo_archive\' + $account.account + $datestr + '.zip') -ErrorAction SilentlyContinue
write-host ("Deleting" + $account.uo_sourcefile)
remove-item -LiteralPath $account.uo_sourcefile -ErrorAction SilentlyContinue
}
# be sure to clean up after ourselves and get ready for next block
Clear-Variable -Name starttime,endtime,sqlresult,sqlcontext,ftp,content,datestr -ErrorAction SilentlyContinue
$error.Clear()
start-sleep -s 2
}
似乎任何抛出的错误都会完全停止作业,并使脚本完全退出而不继续。我将erroractionpreference设置为“继续”或“几乎在任何地方无声地继续”。我不明白为什么会这样
想法?对于-ErrorAction开关和正确处理任何产生的错误,您应该使用Try…Catch结构。这也将使任何错误更容易查明。如果是我,我也会将FTP处理拆分为它自己的函数。