Downloading Medicare Data with Webclient

Challenge

Automate the download of data sets from data.medicare.gov data mart using their Socrata Open Data API (SODA).

Solution

This version pulls Hospital HCAHPS data in XML but can be easily edited to bring back csv or xls formats.

# # Check and Correct the .Net CLR Env settings
if ([Environment]::Version.Major -lt 4) { $configFile = Join-Path $PSHOME -ChildPath '.\powershell.exe.config'if (-not(Test-Path $configFile)) { @' <?xml version="1.0"?> <configuration> <startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0.30319" /> <supportedRuntime version="v2.0.50727" /> </startup> </configuration> '@ | Out-File -FilePath$configFile -Encoding UTF8 "Created $configFile" } 'Restart powershell in order to make it run in .NET 4' }

# Set the extention to xml, csv, xls
$xml_source = "https://data.medicare.gov/resource/jp3v-djai.xml";

# Substitute your password for **PWD**
$dest_pwd = ConvertTo-SecureString "**PWD**" -AsPlainText -Force;

# Specify where to put the downloaded file and make sure the extension matches
$xml_destination = "V:\test.xml";

# Use the default user settings for your enterprise Proxy access
$proxy = [System.Net.WebRequest]::DefaultWebProxy;
$proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials;

# Instantiate the .net WebClient object and call the proxy and credential methods
$Wc = New-Object System.Net.Webclient;
$Wc.Proxy = $proxy;

# Substitute **UID** for your login User ID
$Wc.Credentials = New-Object System.Management.Automation.PSCredential ("**UID**", $dest_pwd);

# Call the actual WebCLient DownloadFile method
$Wc.DownloadFile($xml_source,$xml_destination);

# Return some console message for debugging
if ($Wc -ne 0){Write-Host "Opened $url successfully" -ForegroundColor Red }else {Write-Host "Unable to access $url" -ForegroundColor Yellow }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s