Call REST API from PowerShell Script

后端 未结 3 1496
北恋
北恋 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: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)
    

提交回复
热议问题