Invoke-MetasysMethod.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
using namespace System using namespace System.IO using namespace System.Security using namespace Microsoft.PowerShell.Commands using namespace System.Management.Automation Set-StrictMode -Version 3 # HACK: https://stackoverflow.com/a/49859001 # Otherwise on Linux I get "Unable to find type [WebRequestMethod]" error Start-Sleep -Milliseconds 1 function assertPowershellCore { if ($PSVersionTable.PSEdition -ne "Core") { $errorString = "Windows Powershell is not supported. Please install PowerShell Core" + "`n" + "Windows Powershell is not supported. Please install PowerShell Core" throw $errorString } } function setBackgroundColorsToMatchConsole { # Setup text background colors to match console background $backgroundColor = $Host.UI.RawUI.BackgroundColor $Host.PrivateData.DebugBackgroundColor = $backgroundColor $Host.PrivateData.ErrorBackgroundColor = $backgroundColor $Host.PrivateData.WarningBackgroundColor = $backgroundColor $Host.PrivateData.VerboseBackgroundColor = $backgroundColor } function createErrorStringFromResponseObject { param( [WebResponseObject]$responseObject ) $body = [String]::new($responseObject.Content) $errorMessage = "`nStatus: " + $responseObject.StatusCode.ToString() + " (" + $responseObject.StatusDescription + ")" $responseObject.Headers.Keys | ForEach-Object { $errorMessage += "`n" + $_ + ": " + $responseObject.Headers[$_] } $errorMessage += "`n$body" return $errorMessage } function invokeWithWarningsOff { <# .SYNOPOSIS Invokes a script block with warning preference set to SilentlyContinue This is used in this file to invoke the password management functions that write warnings when called directly by a client. But for which we'd rather not see warnings if they are called by Invoke-MetasysMethod. It seems that I should just be able to invoke my password management functions with -WarningAction SilentlyContinue but that doesn't seem to work. This is my work around for now. #> param ( [ScriptBlock]$script ) $oldWarningPref = $WarningPreference $WarningPreference = "SilentlyContinue" try { & $script } finally { $WarningPreference = $oldWarningPref } } function Invoke-MetasysMethod { <# .SYNOPSIS Sends an HTTPS request to a Metasys device running Metasys REST API .DESCRIPTION This function allows you to call methods of the Metasys REST API. Once a session is established (on the first invocation) the session state is maintained in the terminal session. This allows you to make additional calls with less boilerplate text necessary for each call. .OUTPUTS System.String The payloads from Metasys are formatted JSON strings. This is the default return type for this function. PSObject, Hashtable If the switch `ReturnBodyAsObject` is set then this function attempts to convert the response to a custom object. In some cases, the JSON string may contain properties that only differ in casing and can't be converted to a PSObject. In such cases, a Hashtable is returned instead. .EXAMPLE Invoke-MetasysMethod /objects/$id Reads the default view of the specified object assuming $id contains a valid object identifier .EXAMPLE Invoke-MetasysMethod /alarms This will read the first page of alarms from the site. .EXAMPLE Invoke-MetasysMethod -Method Put /objects/$id/commands/adjust -Body '{ "parameters": [72.5] }' This example will send the adjust command to the specified object (assuming a valid id is stored in $id, and v4 of the API). .LINK https://github.com/metasys-server/powershell-metasysrestapi #> [CmdletBinding(PositionalBinding = $false)] param( # The relative or absolute url for an endpont. For example: /alarms # All of the urls are listed in the API Documentation [Parameter(Position = 0)] [string]$Path, # The payload to send with your request. # # Alias: -b [Parameter(ValueFromPipeline = $true)] [Alias("b")] [string]$Body, # The HTTP Method you are sending. # # Aliases: -m, -verb [Alias("verb", "m")] [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = "Get", # The version of the API you intend to use # # Alias: -v [Alias("v")] [ValidateRange(2, 5)] [Int]$Version, # Skips certificate validation checks. This includes all validations # such as expiration, revocation, trusted root authority, etc. # [!WARNING] Using this parameter is not secure and is not recommended. # This switch is only intended to be used against known hosts using a # self-signed certificate for testing purposes. Use at your own risk. [switch]$SkipCertificateCheck, # A collection of headers to include in the request # # Alias: -h [Alias("h")] [hashtable]$Headers, # Add support for password to be passed in # # Alias: -p [Alias("p")] [SecureString]$Password, # Return the response as PSObject or Hashtable instead of JSON string # Aliases: -o, -object [Alias("o", "object")] [Switch]$ReturnBodyAsObject, # Includes the response headers in the output # # Alias: -rh [Alias("rh")] [Switch]$IncludeResponseHeaders ) BEGIN { Set-Variable -Name fiveMinutes -Value ([TimeSpan]::FromMinutes(5)) -Option Constant setBackgroundColorsToMatchConsole assertPowershellCore if (!$Path) { Write-Information "Path not supplied. Please enter a path" $Path = Read-Host -Prompt "Path" } if (!$SkipCertificateCheck.IsPresent) { $SkipCertificateCheck = [MetasysEnvVars]::getDefaultSkipCheck() } $uri = [Uri]::new($path, [UriKind]::RelativeOrAbsolute) if ($uri.IsAbsoluteUri) { $versionSegment = $uri.Segments[2] $versionNumber = $versionSegment.SubString(1, $versionSegment.Length - 2) if ($Version -gt 0 -and $versionNumber -ne $Version) { Write-Error "An absolute url was given for Path and it specifies a version ('$versionNumber') that conflicts with Version ('$Version')" continue } } If ($Version -eq 0) { # Use the version from last cma call, else the default api version (if set), else latest version $Version = $env:METASYS_VERSION ?? $env:METASYS_DEFAULT_API_VERSION ?? $LatestVersion Write-Information "No version specified. Defaulting to v$Version" } # Login Region if ($null -eq ([MetasysEnvVars]::getToken()) ) { Write-Error "No connection to a Metasys site exists. Please connect using Connect-MetasysAccount" continue } else { if ([MetasysEnvVars]::getExpires()) { $expiration = [MetasysEnvVars]::getExpires() if ([DateTimeOffset]::UtcNow -gt $expiration) { # Token is expired, attempt to connect with previously used site host and user name try { Connect-MetasysAccount -SiteHost ([MetasysEnvVars]::getSiteHost()) -UserName ([MetasysEnvVars]::getUserName()) -Version $Version ` -SkipCertificateCheck:$SkipCertificateCheck } catch { Write-Error "Session expired and attempt to re-connect failed" continue } } elseif ([DateTimeOffset]::UtcNow -gt ($expiration - $fiveMinutes)) { # attempt to renew the token as it will expire soon $uri = buildUri -siteHost ([MetasysEnvVars]::getSiteHost()) -version ([MetasysEnvVars]::getVersion()) -path "/refreshToken" $refreshRequest = buildRequest -uri $uri` -token ([MetasysEnvVars]::getToken()) -skipCertificateCheck:$SkipCertificateCheck try { Write-Information -Message "Attempting to refresh access token" $refreshResponse = Invoke-RestMethod @refreshRequest [MetasysEnvVars]::setExpires($refreshResponse.expires) [MetasysEnvVars]::setTokenAsPlainText($refreshResponse.accessToken) Write-Information -Message "Refresh token successful" } catch { Write-Debug "Error attempting to refresh token" Write-Debug $_ continue } } } } $uri = buildUri -path $Path -version $Version -siteHost ([MetasysEnvVars]::getSiteHost()) } # PROCESS block is needed if you accept input from pipeline like Body in this function PROCESS { $request = buildRequest -uri $uri -method $Method -body $Body -token ([MetasysEnvVars]::getToken()) -skipCertificateCheck:$SkipCertificateCheck ` -headers $Headers $response = $null $responseObject = $null Write-Information -Message "Attempting request" try { $responseObject = Invoke-WebRequest @request -SkipHttpErrorCheck } catch { # Catches errors like host name can't be found but not http errors like 4xx, 5xx due to SkipHttpErrorCheck above Write-Error $_ return } if ($responseObject) { $contentLength = 0 [Int]::TryParse($responseObject.Headers["Content-Length"], [ref] $contentLength) | Out-Null if ($responseObject.Headers["Content-Type"] -like "*json*" -or $contentLength -eq 0 -or $responseObject.StatusCode -eq 204 -or $responseObject.StatusCode -ge 400) { if ($responseObject.Content -is [String]) { $response = $responseObject.Content } else { $response = [System.Text.Encoding]::UTF8.GetString($responseObject.Content) } } else { Write-Error "An unexpected content type was found" Write-Error (createErrorStringFromResponseObject -responseObject $responseObject) } } # Only overwrite the last response if $response is not null if ($null -ne $response) { [MetasysEnvVars]::setLast($response) [MetasysEnvVars]::setHeaders($responseObject.Headers) [MetasysEnvVars]::setStatus($responseObject.StatusCode, $responseObject.StatusDescription) } if ($ReturnBodyAsObject.IsPresent -and $null -ne $response) { Get-LastMetasysResponseBodyAsObject } elseif ($null -ne $response) { if ($IncludeResponseHeaders) { Show-LastMetasysFullResponse } else { Show-LastMetasysResponseBody } } } } function Show-LastMetasysAccessToken { ConvertFrom-SecureString -AsPlainText -SecureString ([MetasysEnvVars]::getToken()) } function Show-LastMetasysHeaders { $response = "" $headers = ConvertFrom-Json ([MetasysEnvVars]::getHeaders()) foreach ($header in $headers.PSObject.Properties) { $response += "$($header.Name): $($header.Value -join ',')" + "`n" } $response } function Show-LastMetasysStatus { ([MetasysEnvVars]::getStatus()) } function ConvertFrom-JsonSafely { param( [String]$json ) try { ConvertFrom-Json -InputObject $json } catch { try { ConvertFrom-Json -AsHashtable -InputObject $json } catch { # apparently this wasn't JSON so leave it as is $json } } } function Show-LastMetasysResponseBody { $body = [MetasysEnvVars]::getLast() if ($body) { ConvertFrom-JsonSafely $body | ConvertTo-Json -Depth 20 } } function Show-LastMetasysFullResponse { "$(Show-LastMetasysStatus)`n$(Show-LastMetasysHeaders)`n$(Show-LastMetasysResponseBody)" } function Get-LastMetasysResponseBodyAsObject { ConvertFrom-JsonSafely ([MetasysEnvVars]::getLast()) } function Get-LastMetasysHeadersAsObject { ConvertFrom-Json ([MetasysEnvVars]::getHeaders()) } function Clear-MetasysEnvVariables { [MetasysEnvVars]::clear() "The environment variables related to the current Metasys sessions have been cleared." } Set-Alias -Name imm -Value Invoke-MetasysMethod Export-ModuleMember -Function 'Invoke-MetasysMethod', 'Show-LastMetasysHeaders', 'Show-LastMetasysAccessToken', 'Show-LastMetasysResponseBody', 'Show-LastMetasysFullResponse', ` 'Get-LastMetasysResponseBodyAsObject', 'Show-LastMetasysStatus', 'Get-LastMetasysHeadersAsObject', 'Clear-MetasysEnvVariables' Export-ModuleMember -Alias 'imm' |