Start a new topic

PowerShell

I was not able to find instructions for accessing the Freshservice API through PowerShell so I am providing a few examples that may benefit of other customers:


   

# Set global variables

$APIKey = 'Your API Key'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = @{}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$HTTPHeaders.Add('Content-Type', 'application/json')

# GET example: get all users (limited to first 50)

$URL = 'https://yourcompany.freshservice.com/itil/requesters.json?state=all'
Invoke-RestMethod -Method Get -Uri $URL -Headers $HTTPHeaders

# PUT example: update a user

$URL = 'https://yourcompany.freshservice.com/itil/requesters/[id].json'
$UserAttributes = @{}
$UserAttributes.Add('name', 'John Doe'
$UserAttributes.Add('phone' , '(123) 456-7890')
$UserAttributes = @{'user' = $UserAttributes}
$JSON = $UserAttributes | ConvertTo-Json 
Invoke-RestMethod -Method Put -Uri $URL -Headers $HTTPHeaders -Body $JSON

   

TL;DR, solution to web exception error as of 2018 is add this to your code: 


 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 


----


Hi John, 


Thanks for this. I have been using this without issues up until around a month ago when i started receiving the below exception:


Invoke-restmethod : The underlying connection was closed: An unexpected error occurred on a send.

At line:13 char:1

+ Invoke-restmethod -Method get -Uri $URL -Headers $HTTPHeaders -verbos ...

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException

    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand 


Issue is related to TLS and how Powershell presents the TLS protocols used by HTTPs. You would probably find this would impact most .NET applications. 


At the moment TLS 1.2 is the latest standard powering SSL, and anything below 1.2 is considered insecure. Its likely Freshservice API devs blocked everything except for 1.2


To ensure it works with .net framework use the following code which will force TLS 1.2 to be used by default. Put it at the start of the request above:


 [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12 


Source


1 person likes this
Login or Signup to post a comment