How to prevent System.Net.WebRequest from printing a bunch of data about the request to the console

359 Views Asked by At

I wrote a powershell script to test a bunch of api endpoints. I grab a list of api endpoints, iterate through them grabbing the status code and checking if things are up and running.

The core of the script is somewhat like the following

$getUris=@(`
  'endpoint1', `
  'endpoint2' `

)

$getUris.foreach({
  $url="$($baseIp)$($PSItem)?companyId=$($companyId)&branchId=$($branchId)"

  $req = [System.Net.WebRequest]::Create($url)
  $req.Credentials = new-object System.Net.NetworkCredential('username', 'password')

  $status
  $response
  try {
    $response = $req.GetResponse()
    $status = [int]$response.StatusCode
  }
  catch [System.Net.WebException] {
    $status = [int]$_.Exception.Response.StatusCode
  }

  if ($response -eq $null) {  }   
  else { $response.Close() }

  if ($successes.ContainsKey([string]$status)) { 
    Write-Host -NoNewLine "$($url): [ "
    Write-Host -NoNewLine "$($successes[[string]$status])" -ForegroundColor 'Green'
    Write-Host " ]" 
  }
  elseif ($errors.ContainsKey([string]$status)) {
    Write-Host -NoNewLine "$($url): [ "
    Write-Host -NoNewLine "X" -ForegroundColor 'Red' 
    Write-Host -NoNewLine ' ] - ' 
    Write-Host "$([string]$status) ($($errors[[string]$status]))" -ForegroundColor 'Red'
  }
  else {echo "$($url): [Erro desconhecido"}
})

The output comes like this

Testando endpoints GET
endpoint1: [ √ ]
endpoint2: [ √ ]
200


IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Content-Length, Content-Type, Date, Server}
SupportsHeaders         : True
ContentLength           : 3069
ContentEncoding         :
ContentType             : application/json; charset=utf-8
CharacterSet            : utf-8
Server                  : Microsoft-HTTPAPI/2.0
LastModified            : 08/02/2022 16:39:05
StatusCode              : OK
StatusDescription       : OK
ProtocolVersion         : 1.1
ResponseUri             : endpoint1
                          d=17
Method                  : GET
IsFromCache             : False

200
IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Content-Length, Content-Type, Date, Server}
SupportsHeaders         : True
ContentLength           : 1915
ContentEncoding         :
ContentType             : application/json; charset=utf-8
CharacterSet            : utf-8
Server                  : Microsoft-HTTPAPI/2.0
LastModified            : 08/02/2022 16:39:05
StatusCode              : OK
StatusDescription       : OK
ProtocolVersion         : 1.1
ResponseUri             : endpoint2
Method                  : GET
IsFromCache             : False

It should've ended in the last line with the checkmark, but it keeps printing a load of information about the request that I didn't ask for. Anyone have any idea of what I did wrong?

0

There are 0 best solutions below