Test WebClient API call

2019-09-14 13:44发布

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条回答
别忘想泡老子
2楼-- · 2019-09-14 13:58

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    
}
查看更多
登录 后发表回答