Call REST API from PowerShell Script

后端 未结 3 1492
北恋
北恋 2020-12-24 01:29

How can I call a rest based API from a PowerShell script and process the Json answer?

相关标签:
3条回答
  • 2020-12-24 01:32

    What you want is PowerShell 3 and its Invoke-RestMethod, ConvertTo-Json, and ConvertFrom-Json cmdlets. Your code will end up looking like:

     $stuff = Invoke-RestMethod -Uri $url -Method Get;
    

    and there shouldn't even be a need to invoke ConvertFrom-Json on the resulting $stuff => it's already in a usable non-string format.

    See http://technet.microsoft.com/en-us/Library/hh849971.aspx for details.

    0 讨论(0)
  • 2020-12-24 01:49

    I created this Get-Http function to make HTTP requests

    param([string]$url)
    
    $req = [System.Net.WebRequest]::Create($url)
    $req.Method ="GET"
    $req.ContentLength = 0
    
    $resp = $req.GetResponse()
    $reader = new-object System.IO.StreamReader($resp.GetResponseStream())
    $reader.ReadToEnd()
    

    Dealing with the end result as xml is really easy, however, if you want to process JSON you probably will need some .Net library like JSON.Net.

    0 讨论(0)
  • 2020-12-24 01:54

    We use Powershell to query a REST API that deals only with Json style data. It was awkward at first but the below code is all we need to perform most operations:

    # Authentication
    $webclient = New-Object System.Net.WebClient
    $creds = New-Object System.Net.NetworkCredential("MyUsername","MyPassword");
    $webclient.Credentials = $creds
    
    # Data prep
    $data = @{Name='Test';} | ConvertTo-Json
    
    # GET
    $webClient.DownloadString($url) | ConvertFrom-Json
    
    # POST
    $webClient.UploadString($url,'POST',$data)
    
    # PUT
    $webClient.UploadString($url,'PUT',$data)
    
    0 讨论(0)
提交回复
热议问题