Data science is all the rage these days, but data science requires data. PowerShell may usually be thought of as a Sysadmin utility, but it can be used for an absolutely amazing number of process automation and business automation tasks, including gathering raw data for use by other applications.
In this example we will gather the population data for each state in the USA, using Census data. Here is some metadata on our source:
Now, let’s get to work, first by creating our function declaration, which we will call “statepop”, in this case.
The above is recommended so that you can use the function again and again, within the same PowerShell session, as needed. If you want to retain this beyond one session, you would want to store the function in your PowerShell profile (beyond the scope of this tutorial).
Above we assign our $zurl variable and enable TLS 1.2. Remember that, by default (at the time of this writing) many Windows Servers do not respect TLS 1.2 for SSL communication (which breaks interaction with many data-sources).
Above we use the now-familiar (if you follow the series) $zdata variable to store data downloaded from the URL we have stored in $zurl.
The actual information we want to work with here comes from the “data” subset of our $zdata dataset, so above we copy that information into a separate variable, called “$zstateData”.
Above we take our state population data and sort it alphabetically, by state name. Note that we have changed the case of the “D” within “$zstateData”, with no effect on usability. Inconsistent case makes for sloppy scripting, and creates bad habits when transitioning to other operating systems which care ALOT about case (like Linux) but is worthwhile for tutorial purposes.
And now (above) we loop through our state population data, item by item, and display the data in a color-coded fashion (state label in yellow, and population data in white).
Next you will want to close out your function with a “}” on its own line and then you are clear to run your new function.
And there we have it. United States population data, by state, color coded, using PowerShell. This method could be programmatically used to populate a CSV file, for example, for use later. Here is a way to do that, as a bonus:
And here is what part of that data looks like, in CSV format, within PowerShell:
You now know how to retrieve, format, display, and export population data for each US state (as reported by the data source) using Windows PowerShell.
Use the power for Good instead of Evil. Please.
And be sure to tip, if you found this valuable enough.