Last active
          March 23, 2022 14:18 
        
      - 
      
- 
        Save jrotello/8873462 to your computer and use it in GitHub Desktop. 
    Powershell helper to ease Elasticsearch interaction without curl
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function Invoke-Elasticsearch { | |
| [CmdletBinding()] | |
| Param( | |
| [Uri]$Uri, | |
| [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = 'Get', | |
| $Body = $null, | |
| [PSCredential]$Credential | |
| ) | |
| $headers = @{} | |
| if ($Credential -ne $null) { | |
| $temp = "{0}:{1}" -f $Credential.UserName, $Credential.GetNetworkCredential().Password | |
| $userinfo = "Basic {0}" -f [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($temp)) | |
| $headers.Add("Authorization", $userinfo) | |
| } elseif ($Uri.UserInfo -ne "") { | |
| $userinfo = "Basic {0}" -f [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Uri.UserInfo)) | |
| $headers.Add("Authorization", $userinfo) | |
| } | |
| $response = try { | |
| Invoke-WebRequest -Method $Method -Uri $Uri -Body $Body -Headers $headers | |
| } catch { | |
| if ($_.Exception.Response -eq $null) { | |
| Write-Error $_.Exception | |
| } | |
| $webResponse = New-Object Microsoft.PowerShell.Commands.WebResponseObject($_.Exception.Response, $_.Exception.Response.GetResponseStream()) | |
| $content = [System.Text.Encoding]::UTF8.GetString($webResponse.Content) | |
| $webResponse | Select StatusCode, StatusDescription, Headers, @{Name="Content"; Expr={$content}} | |
| } | |
| Write-Verbose ("{0} {1}" -f $response.StatusCode, $response.StatusDescription) | |
| $response | Select StatusCode, StatusDescription, Headers, Content | Write-Output | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment