saravanan
saravanan

Reputation: 408

Triggering a long running job in azure VM Asynchronously using powershell

I have a job that runs for a long time. I need to start running that in an azure vm and return without waiting for it to complete. My code is

$code='New-Item -Path "C:\windows\System32\Ds\dir1" -ItemType directory -ErrorAction Ignore
       Start-Sleep -s 100
       New-Item -Path "C:\windows\System32\Ds\dir2" -ItemType directory -ErrorAction Ignore
      '

Invoke-Command -ConnectionUri $WinRMUri -Credential $Cred -ScriptBlock{param($code)
                                                                      $sb = [ScriptBlock]::Create($Code)                                                                                                                                                            
                                                                      $job=Start-job -ScriptBlock $sb 
                                                                      }-ArgumentList $code

But I see only the first directory is getting created. So I assume the job is killed while the session returns from the Azurevm. But I need the job to be continue running in that vm. How to achieve this ?

Upvotes: 0

Views: 457

Answers (1)

Robert R.
Robert R.

Reputation: 681

I Created an Function for this I often use. You can Invoke the Command with "-AsJob" then it runs in the Background.

$V contains $(Get-AzureVM -Name Name -ServiceName Service).
$cred contians the credentials.
$CMD is the command.

...and it has very simple Errorhandling

Function InvokeCommand ( $V, $cred, $CMD )
    {
    $PSSO = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck # Disable Cert Checks
    $S = Get-AzureVM -ServiceName $ServiceName -Name $V.Name -Verbose:$false
    $N = ($S.VM.ConfigurationSets | where { $_.ConfigurationSetType -eq "NetworkConfiguration" }).InputEndpoints | where { $_.LocalPort -eq "5986" }
    $U = "https://" + $N.VIP + ":" + $N.Port
    $Action = "SilentlyContinue"

    $Error.clear()
    Invoke-Command -ConnectionUri $U -Credential $cred -ScriptBlock ([scriptblock]::Create($CMD)) -SessionOption $PSSO -ErrorAction:$Action
    if ( $Error.count -eq 0 )
        { return $true }
    elseif ( $Error.Count -ne 0 )
        {
        if ( $Error[0].Exception -like "*Please restart the computer before trying to install*" )
            { 
            $Error.Clear()
            return $true
            }
        }
    return $false
    }

Upvotes: 1

Related Questions