I am creating a class in powershell to manage authorization to an api. Now if for some reason the connection fails, i want to return a message and a return code.
I have a constructor, this one is calling a static method (thus i am not able to use $this...). Found some example (not used in a class though) explaining i could create a hashtable to return from my method, but for some reason this does not work.
Class ApiAuth
{
[string] $APIUser
hidden [string] $ApiPassword
[string] $ApiUrl
[string] $authorization
hidden [string] $bodyParams
[int] $ReturnCode
ApiAuth([string] $APIUser, [string] $ApiPassword, [string] $ApiUrl)
{
Write-Host "HIER1" -ForegroundColor Yellow
$this.APIUser = $APIUser
$this.ApiPassword = $ApiPassword
$this.ApiUrl = ($ApiUrl, "Login") -join "/"
$this.bodyParams = @{"UserName"= $this.APIUser; "Password" = $this.ApiPassword} | ConvertTo-Json
$t1 = [ApiAuth]::Connect($this.ApiUrl, $this.bodyParams)
Write-Host $t1.Length -ForegroundColor Cyan
Write-Host $t1.ToString() -ForegroundColor RED
Write-Host $t1['auth'] -ForegroundColor Yellow
Write-Host $t1.code -ForegroundColor GREEN
#Write-Host $temp[1] -ForegroundColor Yellow
}
Reconnect()
{
$this.authorization = [ApiAuth]::Connect($this.ApiUrl, $this.bodyParams)
}
static [String] Connect([string] $ApiUrl, [string] $bodyParams)
{
try {
$rest = Invoke-WebRequest -Uri $ApiUrl -Method POST -Body $bodyParams -ContentType 'application/json'
#
#$this.ReturnCode = [int]$_.Exception.Response.StatusCode
$ret = @{}
$ret.auth = $rest.Headers.Authorization
$ret.code = [int]$_.Exception.Response.StatusCode
return $ret
#Return $rest.Headers.Authorization
#Return $rest.Headers.Authorization, [int]$_.Exception.Response.StatusCode
}
catch [System.Net.WebException] {
Write-Host "HIER2" -ForegroundColor RED
Write-Host $_.Exception -ForegroundColor RED
#$this.ReturnCode = [int]$_.Exception.Response.StatusCode
if([int]$_.Exception.Response.StatusCode -eq 401) {
}
return $false
}
catch {
Write-Host "HIER3" -ForegroundColor RED
#$this.ReturnCode = [int]$_.Exception.Response.StatusCode
return $false
}
}
}
Now i am looking for a way to return multiple values to act on this accordingly. Or maybe i can call "Connect()" without making it static?