Hi guys,
I’m new to PowerShell background jobs, I read the help documentation about jobs and I think I need to use the jobs to avoid one of my current conundrum.
I have a PS script that connects to SQL server and does some inserts and updates to a SQL Azure table.
The PS script is invoked via SQL Server Agent, every 3 minutes.
Sometimes the script of inserting and updating data takes more than 3 minutes to complete, in which SQL Server agent invoke the PS script again (because it’s running every 3 minutes) and now I have a deadlock error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Transaction (Process ID 127) was deadlocked on lock | communication buffer resources with another process and has been chosen as the deadlock victim. Rerun the transaction." - Line Number: 528
So, I have been dabbling with the below script, the idea is to invoke my script as a job, then get-job to see if the job still running and if it’s still running don’t do anything comeback after 3 minutes and check on this job again.
I have noticed that the Job runs under current session. Which means if I do get-job on a different session of PowerShell the running job won’t show up in the new session.
So my question is
- Am I approaching this issue the right way?
- Is there a way of running the job “globally” on the server so when Invoke command Get-Job I can see if the job is still running?
Here is a small script that I have put together for this question:
$Jobs = Get-Job If ($Jobs.Count -eq 0) { Start-Job -FilePath "C:\Users\MyUserName\OneDrive - MyCompany\MyCompany\PowerShell\Test\Get-Processes.ps1" -Name "Job-Get-Process" } Else { ForEach ($Job in $Jobs) { $JobState = $Job.State Switch ($JobState) { "Completed" { #Remove the Job $Job | Export-Csv -Path "C:\Users\MyUserName\OneDrive - MyCompany\MyCompany\PowerShell\Test\Jobs.csv" -NoTypeInformation -Append $Job | Remove-Job Start-Job -FilePath "C:\Users\MyUserName\OneDrive - MyCompany\MyCompany\PowerShell\Test\Get-Processes.ps1" -Name "Job-Get-Process" } "Failed" { #Remove the job then re-run it $Job | Export-csv -Path "C:\Users\MyUserName\OneDrive - MyCompany\MyCompany\PowerShell\Test\Jobs.csv" -NoTypeInformation -Append $Job | Remove-Job } "Running" { #Do nothing come back after 3 minutes to see if this job is completed or failed. $Job | Export-csv -Path "C:\Users\MyUserName\OneDrive - MyCompany\MyCompany\PowerShell\Test\Jobs.csv" -NoTypeInformation -Append } } } }