How to use Powershell Invoke-RestMethod to extract information from server using REST API?
AnsweredHello
I'm trying to create a Powershell script to poll our various NX Servers via their REST API and extract system info e.g. version etc and the Users.csv file.
The URL works in a browser (with a credentials prompt) however I always get the following error via PS:
"The underlying connection was closed: An unexpected error occurred on a send."
What more is required?
Here is my (cleaned) sample script:
# Define the REST API URL
$apiUrl = "https://HOST1:7001/rest/v2/users?_format=CSV"
# Define authentication credentials if required
$username = "AdminUser"
$password = "WorkingPwd"
$credential = New-Object System.Management.Automation.PSCredential($username, (ConvertTo-SecureString $password -AsPlainText -Force))
# Ignore SSL/TLS certificate validation errors
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
# Define TLS version and ciphers (optional)
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12, [Net.SecurityProtocolType]::Tls11, [Net.SecurityProtocolType]::Tls
# Invoke REST API and download the CSV file
try {
$response = Invoke-RestMethod -Uri $apiUrl -Credential $credential -Method Get -Verbose
$response | Out-File -FilePath "users.csv"
Write-Host "CSV file downloaded successfully."
} catch {
Write-Host "Failed to download CSV file. Error: $_"
}
-
Hi RTF-Admin,
Thanks for your question and it is glad to see people using all the different tools doing their daily routines or tasks in a smart way.
Regarding to the error, that is highly likely the self-signed certificates. This is neither a bug nor an issue but simply you need to deal with the self-signed certificates in your powershell implementation.
I assume you were using powershell v5.1, which is a little bit out-of-date that missing some essential features and options for modern security requirements.
There would be two possible solutions.
1) Update and install the powershell 7.4. The good news is that 7.4 can sit aside with 5.1., so literally you just need to install 7.4 on the device that you run powershell script.
https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell-on-windows?view=powershell-7.4#installing-the-msi-package2) You need to override the callback function -
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type) { $certCallback = @" using System; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; public class ServerCertificateValidationCallback { public static void Ignore() { if(ServicePointManager.ServerCertificateValidationCallback ==null) { ServicePointManager.ServerCertificateValidationCallback += delegate ( Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors ) { return true; }; } } } "@ Add-Type $certCallback } [ServerCertificateValidationCallback]::Ignore()
So, to be honest, using PS6 or just PS7.4 would be way much easier, it would be just one more option, called -SkipCertificateCheck
$response = Invoke-RestMethod -Uri $apiUrl -Credential $credential -Method Get -SkipCertificateCheck -Verbose
Last, if you don't mind, you may refer to the sample ps1 file attached.
# Define the REST API URL
$serverIp = "127.0.0.1"
$apiUrl = "https://$($serverIp):7001/rest/v2/users?_format=CSV"
# Define authentication credentials if required
$username = "admin"
$password = "Your Password"
#You are asked to enable the digest authentication of the specific account
#$credential = New-Object System.Management.Automation.PSCredential($username, (ConvertTo-SecureString $password -AsPlainText -Force))
# Using the recommended authentication option - OAuth2, Bearer token
$token = ConvertTo-SecureString "Your Own Token" -AsPlainText -Force
# Ignore SSL/TLS certificate validation errors
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
# Define TLS version and ciphers (optional)
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Invoke REST API and download the CSV file
try {
$response = Invoke-RestMethod -Uri $apiUrl -Method Get -SkipCertificateCheck -Verbose -Authentication Bearer -Token $token
#$response = Invoke-RestMethod -Uri $apiUrl -Method Get -SkipCertificateCheck -Verbose -Credential $credential
$response | Out-File -FilePath "users.csv"
Write-Host"CSV file downloaded successfully."
} catch {
Write-Host"Failed to download CSV file. Error: $_"
}1 -
Thanks Ichiro, your above guide is good. We were using PSv5.1 so by forcing the use of PSv7 with the -SkipCertificateCheck, it all worked.
We'll now use this solution to routinely audit the multitude of stand-alone NX systems we have at our sites.
Cheers0
Please sign in to leave a comment.
Comments
2 comments