# LEAPWORK REST API example: Run a schedule, iterate through the results and create incidents in ServiceNow.# #Global Variables $controllerHostNameOrIPAddress="localhost" $controllerPort="9001" $APIAccesskey="12345" $scheduleName="SmokeRunSchedule" $serviceNowUser = "username" $serviceNowPass = "password" $serviceNowInstance = "https://yourdomain.service-now.com" $incidentOwnerEmail = "callie.leboeuf@example.com" # Function that finds a schedule in LEAPWORK based on a title, runs it, and polls for the results. function RunScheduleAndGetResults($schedule) { Write-Host "Getting id for schedule '$schedule'." # Get the id of the schedule. $runScheduleId = ""; $headers = @{} $headers.Add("AccessKey",$APIAccesskey) $controllerURL=$controllerHostNameOrIPAddress + ":" + $controllerPort $runSchedules = Invoke-WebRequest -ContentType "application/json" -Headers $headers "http://$controllerURL/api/v3/schedules" | ConvertFrom-Json foreach($runScheduleItem in $runSchedules) { if ($runScheduleItem.title -eq $schedule) { $runScheduleId = $runScheduleItem.id } } if ($runScheduleId -eq "") { throw "Could not find schedule '$schedule'." } Write-Host "Running the schedule." # Run the schedule now. $timestamp = [DateTime]::UtcNow.ToString("ddMMyyyy HHmmss") Start-Sleep 1 $runNow = Invoke-WebRequest -Method PUT -ContentType "application/json" -Headers $headers "http://$controllerURL/api/v4/schedules/$runScheduleId/runNow" if ($runNow.StatusCode -ne 200) { throw "Could not run schedule." } $runNowResponse=$runNow.Content | ConvertFrom-Json $runId=$runNowResponse.RunId # Get the result, keep polling every 5 seconds until a new result is returned. do { Start-Sleep -Seconds 5 Write-Host "Polling for run results." $runResult = Invoke-WebRequest -ContentType "application/json" -Headers $headers "http://$controllerURL/api/v4/run/$runId" | ConvertFrom-Json } while ($runResult.Status -ne 'Finished') Write-Host "Results received." return $runResult } # Function that creates an Incident with a specific title in ServiceNow. function CreateBug($incidentTitle, $incidentDescription) { # Build auth header $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $serviceNowUser, $serviceNowPass))) echo $base64AuthInfo # Set proper headers $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo)) $headers.Add('Accept','application/json') [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls" # Specify endpoint uri to find owner/caller ID $userQueryURL = $serviceNowInstance + "/api/now/table/sys_user?sysparm_query=email%3D" + $incidentOwnerEmail.Replace("@", "%40") echo $userQueryURL # Send HTTP request to find caller ID $userDetail = Invoke-WebRequest -ContentType "application/json" -Headers $headers -Method GET -Uri $userQueryURL | ConvertFrom-Json # Parameters $params = @{"short_description"= $incidentTitle; "description"= $incidentDescription; "caller_id" = $userDetail.Result.sys_id; } echo $userDetail.Result.sys_id # Specify endpoint uri to create new incident $queryURL = $serviceNowInstance + "/api/now/v1/table/incident" # Send HTTP request $reponse = Invoke-WebRequest -ContentType "application/json" -Headers $headers -Method POST -Body ($params|ConvertTo-Json) -Uri $queryURL | ConvertFrom-Json echo $reponse } # Run the LEAPWORK schedule "My Test Schedule" and get the results. $runResult = RunScheduleAndGetResults($scheduleName) # If there are any failed cases in the results, iterate through them. if ($runResult.Failed -gt 0) { Write-Host "Found $($runResult.Failed) failed case(s)." $headers = @{} $headers.Add("AccessKey",$APIAccesskey) $controllerURL=$controllerHostNameOrIPAddress + ":" + $controllerPort $runId=$runResult.RunId $runItemIds = Invoke-WebRequest -ContentType "application/json" -Headers $headers http://$controllerURL/api/v4/run/$runId/runItemIds | ConvertFrom-Json $rootPath =$runResult.RunFolderPath foreach ($runItemId in $runItemIds.RunItemIds) { $runItems = Invoke-WebRequest -ContentType "application/json" -Headers $headers http://$controllerURL/api/v4/runItems/$runItemId | ConvertFrom-Json if($runItems.FlowInfo.Status -eq 'Failed') { # Create a title for the bug. $incidentTitle = "LEAPWORK: " + $runItems.FlowInfo.FlowTitle # Create a description that contains the log messages. $newline = "\r\n"; $keyFrames = Invoke-WebRequest -ContentType "application/json" -Headers $headers http://$controllerURL/api/v4/runItems/$runItemId/keyframes/1 | ConvertFrom-Json $incidentDescription = "Log from LEAPWORK:$newline $newline" foreach ($keyframe in $keyFrames) { if ($keyframe.Level -ge 1) { $keyframeTimestamp = get-date($keyframe.Timestamp.LocalDateTime) -Format "dd-MM-yyyy HH:mm:ss" $incidentDescription += "$keyframeTimestamp - $($keyframe.LogMessage) $newline" } } # Add path to video and screenshots. $mediaPath = Join-Path -Path $rootPath "$($runItems.RunItemId)" $videoPath = Join-Path -Path $mediaPath "$($runItems.RunItemId).avi" $videoPath = $videoPath.Replace('\', '\\') $screenshotsPath = Join-Path -Path $mediaPath "Screenshots" $screenshotsPath = $screenshotsPath.Replace('\', '\\') $incidentDescription += "$newline Video: $videoPath $newline" $incidentDescription += "$newline Screenshots (if any): $screenshotsPath $newline" # Create or update bug in ServiceNow. CreateBug $incidentTitle $incidentDescription } } } else { Write-Host "No failed cases found." }