0

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?

  • 2
    I have already commented on your previously deleted question that the data is likely coming from `$status` or `$response` or both. – Santiago Squarzon Feb 08 '22 at 21:44
  • 1
    Sorry about that! Had to delete due exposed api endpoints. Why would it be coming from them if I'm not consoling them? Also, it seems like it happens as the last step of the loop and it always prints 1 less dump than endpoints.. Weird – Gabriel Lüders Feb 08 '22 at 22:15
  • 1
    `Write-Host` has priority to display things in the console hence why you first see all `Write-Host` statements, and then you see the output from both variables, you can force the output of the variables to the console on each iteration using `Out-Host`. i.e.: `$status | Out-Host` and `$response | Out-Host` – Santiago Squarzon Feb 08 '22 at 22:19
  • Is there a way I can prevent them from being consoled at all? Why does it seem that they are being consoled if I'm not even coding that behavior – Gabriel Lüders Feb 08 '22 at 22:35
  • 1
    That's how PowerShell works, any variable that is not captured or redirected will be output to the console. If you don't want to see the content of those variables just remove them from your loop :) This answer, even tho it was for _functions_ still provides a lot of context an useful information about PowerShell behavior https://stackoverflow.com/a/69792182/15339544 – Santiago Squarzon Feb 08 '22 at 22:39
  • @GabrielLüders Simply remove the two lines containing `$status` and `$response` on their own. – Mathias R. Jessen Feb 08 '22 at 23:14
  • 2
    @SantiagoSquarzon I never thought about `Write-Host` having priority, and changing the order things are displayed in. I was scratching my head why things in the loop weren't displaying in the order I expected them to. Thanks for pointing that out. – TheMadTechnician Feb 08 '22 at 23:16
  • @TheMadTechnician I don't know if "priority" is the appropriate word but I just know, `Write-Host` goes always first to the console unless `Out-Host` or `Out-Default`, a simple way of testing the theory is `(0..10).ForEach({ $_; Write-Host "$_ from Write-Host" })` – Santiago Squarzon Feb 08 '22 at 23:27
  • Got it, thanks guys. Now, can I redirect it to somewhere other than stdout? I'm going to try to remove them, however I still need to close the response when it happens, that's the main reason I was keeping it in a variable. Also, the status is being used to index pretty much every hash map of information that I have... – Gabriel Lüders Feb 08 '22 at 23:35
  • @GabrielLüders for sure it will work if you remove both variables from there. Promise :) – Santiago Squarzon Feb 08 '22 at 23:39
  • 1
    @SantiagoSquarzon Thanks for all your help. Didn't remove the variables because it would cause too musch headache, insetead I passed `$null` to them at the end of every loop iteration. That did it! – Gabriel Lüders Feb 08 '22 at 23:48

0 Answers0