Import-ValidCSV Powershell Function
I often find myself working with CSV files when I'm writing PowerShell or PowerCLI scripts. Of course, PowerShell has the native Import-CSV cmdlet, which works well... but it doesn't have much error checking. After writing a bunch of script specific error checking, I've finally broken down and put together a function to do it for me. Now, I can either add this function to my PowerShell profile, or just include it in any scripts that need it.
The function is called Import-ValidCSV. It basically just calls the normal Import-CSV cmdlet, but accepts a second arguement: -RequiredColumns. The -ReqiredColumns argument is set up to accept an array of strings, listing all of the column headers that are required (duh!). The function iterates through the list of RequiredColumns and checks that each column exists in the supplied CSV file. If a column does not exist, it throws an error and quits. If all columns exist (really, just if it doesn't throw an error and quit), it returns the output of the normal Import-CSV cmdlet.
The function is called Import-ValidCSV. It basically just calls the normal Import-CSV cmdlet, but accepts a second arguement: -RequiredColumns. The -ReqiredColumns argument is set up to accept an array of strings, listing all of the column headers that are required (duh!). The function iterates through the list of RequiredColumns and checks that each column exists in the supplied CSV file. If a column does not exist, it throws an error and quits. If all columns exist (really, just if it doesn't throw an error and quit), it returns the output of the normal Import-CSV cmdlet.
Comments
Post a Comment
Sorry guys, I've been getting a lot of spam recently, so I've had to turn on comment moderation. I'll do my best to moderate them swiftly after they're submitted,