Search code examples
powershelljobsinvoke-sqlcmd

Start-Job PowerShell two jobs getting created


I want to execute set of un-contained stored procedures, as jobs, to see if there are any issues in the code after making the database as contained database. After some time, I want to see whether the stored procedures are successful or not. But, I see that instead of one job for a stored procedure, two jobs are getting created. How to avoid the creation of two jobs?

$unContainedSProcs = Import-Csv -Path C:\DFLog\UnContained_Parameterless_SPs.csv
$batchSize = 50
$currentCompletedIdx = 0
$jobIds = @()
$scriptToExecute = {
    Param($storedProcToExecute)
    Invoke-Sqlcmd -Query "Exec $storedProcToExecute" -ServerInstance "<<ServerInstance>>" -Database "<<Database>>" -QueryTimeout 120
}

while ($currentCompletedIdx -le $unContainedSProcs.Length) {
    for ($i= 0; $i -le $batchSize; $i++) {
        $job = Start-Job -Name $unContainedSProcs[$i].UnContainedSProcName -ScriptBlock $scriptToExecute -ArgumentList $unContainedSProcs[$i].UnContainedSProcName
        $jobIds += $job.Id
        ++$currentCompletedIdx
    }
}

When I see the jobs list, using Get-Job, I see two jobs:

+----+--------------+------------------+-----------+---------------+--------------+------------------------------+
| Id |     Name     | PSJobTypeName    |   State   |   HasMoreData |   Location   |           Command            |
+----+--------------+------------------+-----------+---------------+--------------+------------------------------+
|  1 |   dbo.SPName | BackgroundJob    | Completed |  True         |    localhost |    param($storedProcToExe... |
| 41 |  Job41       | BackgroundJob    | Completed |  True         |    localhost |    param($storedProcToExe... |
+----+--------------+------------------+-----------+---------------+--------------+------------------------------+

Solution

  • I have figured it out. It is due to wrong definition of for loop condition. When the number of stored procedures is 1 and for loop is running twice: 0, 1. It is due to -le (less than or equal to) Length of $unContainedSProcs(1).

    There is only one entry [0] in $unContainedSProcs. For the first run, it is fine. For second run, there is no entry[1] in $unContainedSProcs. So, empty job is getting created. After changing -le to -lt, there is only one job created.

    From:

    for ($i= 0; $i -le $batchSize; $i++) {
    

    To:

    for ($i= 0; $i -lt $batchSize; $i++) {