0

I have the following PowerShell script that makes an API Rest GET call.

$FullURL = "http://test.net/config/server/$($env:COMPUTERNAME)?format=test"
$API = New-Object System.Net.WebClient
$APIData = $API.DownloadString($FullURL)
Set-Content -Value $APIdata -Path $APIDataFile -Force

The call is dependent on the local hostname in the URI. It gets the data and exports to a text file as a backup. The problem - the API host maybe down or no information available for the host which will cause all sorts of errors in the script (this is a small part of the script as it adds the data to an XML file).

How do I add logic to the script to test the API call first, if the successfully then continue with making the API call?

It must work for PowerShell 2.0 because of windows 2003 hosts. API is gives an error 404 code if the theres no data.

1 Answer 1

2

You need to use a try/catch block. WebClient should raise an exception when the download isn't successful. Try something like:

$FullURL = "http://test.net/config/server/$($env:COMPUTERNAME)?format=test"
try {
    $API = New-Object System.Net.WebClient
    $APIData = $API.DownloadString($FullURL)
    Set-Content -Value $APIdata -Path $APIDataFile -Force
}
catch [Net.WebException] {
    # Do whatever you want if an exception is raised    
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your help. I am getting the following error - Unable to find type [Webexception]: make sure that the assembly containing this type is loaded. I changed the hostname to one that doesnt exist to test. Any ideas
Thanks, found the Net.webexception in another stackoverflow question as well. Working perfectly. Do you know what [net.webexception] does? just for my learning. Thanks
It defines an exception of that type, it doesn't really do anything. Suggest you find an introduction to error handling in .NET, that will go over what exceptions are, when they're thrown and how to handle them. WebException is explained here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.