Search code examples
azurepowershellazure-runbook

Powershell script working in ISE, but not working in Azure Runbook


I have a powershell script as follows:

$headers = @{}
$headers.Add('ApiKey','xxx')
$file = 'xxx.zip'
Invoke-WebRequest "https://myurl/Export/" -Headers $headers -Outfile $file

This works perfectly on my local PC, but when I run it in an Azure runbook I get:

Response status code does not indicate success: 400 (Bad Request).

Could it be the version of Powershell that is the issue, or any other ideas?

Have run it locally from a cmd prompt using Powershell -file and it works. Running it in the Azure runbook does not work.


Solution

  • Powershell script working in ISE, but not working in Azure Runbook

    There are multiple reasons for the error 400 Bad Request in an Automation Account.

    Make sure to check that the PowerShell version in the Azure runbook is compatible with the script and also verify network restrictions

    Here is an updated PowerShell script to capture more details about the request and response.

        $PSVersionTable.PSVersion
        
        Test-NetConnection -ComputerName "jsonplaceholder.typicode.com" -Port 443
        $headers = @{}
        $headers.Add('ApiKey', 'test-api-key') 
        $file = 'test-response.json'
        $url = "https://jsonplaceholder.typicode.com/posts"
        Write-Output "Headers: $($headers | Out-String)"
        try {
            $response = Invoke-WebRequest -Uri $url -Headers $headers -OutFile $file -ErrorAction Stop
            Write-Output "Response: $($response | Out-String)"
        } catch {
            Write-Output "Error: $_"
            if ($_.Exception.Response) {
                $responseStream = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream())
                $responseBody = $responseStream.ReadToEnd()
                Write-Output "Response Body: $responseBody"
            }
        }
    

    Output:

    Note: In my case, I have used a public URL and sample data with runtime version 5.1.

    enter image description here

    If there is any issue in the script, it will catch the error and display it as shown below

    enter image description here