Powershell - check csv format

Posted on 2016-11-15
Medium Priority
Last Modified: 2016-11-17
Hello I want to import a users.csv to create new AD users but I want to check its in the correct format first, how can I do this in powershell? Checking correct column headings, maybe also checking the entire contents not containing illegal characters like hyphens, apostrophes etc..

Any advice please?
Question by:Pete
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Expert Comment

by:Niten Kumar
ID: 41888888
What is the format of your csv file?  Best would be if you use a proper template where the required data is input correctly then there should be no issues.  See attached .xls file.  You can modify it to your requirements.  The instructions are on the first sheet.

Author Comment

ID: 41889281
That is not the answer to the question, I know what a properly formatted csv should look like, I want to script in some protection in case it is wrong.

Expert Comment

by:Kevin Stanush
ID: 41889826
What Niten is suggesting, and I'll second, is that Powershell might not be the best tool for doing this 'validation'.  You are going to have to read each line from the CSV file, and then perform custom checks on it, based on your own needs, like not allowing certain characters, checking length, if each element is supplied, etc.

It might be easier and more efficient to perform these checks before the file is created.
LVL 85

Accepted Solution

oBdA earned 2000 total points
ID: 41891224
Here's a starting point. The first part checks if all expected headers appear in the csv; this can be used pretty universally.
The content check you're going to have to customize yourself; I've put some samples in on how it could be done.
$Csv = Import-Csv -Path "C:\Temp\ADUser.csv"

## List all columns that MUST be in the csv:
$ColumnsExpected = @(
## Error and help messages for the content:
Function Set-ContentError($Index, $Column, $Value) {
	"Row $($Index), column '$($Column)': value '$($Row.$Column)' is invalid!" | Write-Host -ForegroundColor Red
	$HelpMessage = Switch ($Column) {
		'SamAccountName'	{'Allowed characters are a-z, 0-9, -, maximum length 20.'}
		'DisplayName'		{'No single quotes, please.'}
	If ($HelpMessage) {$HelpMessage | Write-Host -ForegroundColor Yellow}
	Return $False

## Verify that all expected columns are there (additional columns in the csv will be ignored)
$ColumnsOK = $True
$ColumnsCsv = $Csv | Get-Member -MemberType NoteProperty | Select-Object -ExpandProperty Name

$ColumnsExpected | ForEach-Object {
	If ($ColumnsCsv -notcontains $_) {
		$ColumnsOK = $False
		"Expected column not found: '$($_)'" | Write-Host -ForegroundColor Red

If (-not $ColumnsOK) {
	Throw "The csv format is incorrect!"

## Verify that the contents are OK:
$ContentOK = $True
$RowIndex = 0
ForEach ($Row In $Csv) {
	$Column = 'SamAccountName'
	If (-not ($Row.$Column -match '\A[-a-z0-9]{1,20}\Z')) {
		$ContentOK = Set-ContentError -Index $RowIndex -Column $Column -Value $Row.$Column
	$Column = 'DisplayName'
	If ($Row.$Column.Contains("'")) {
		$ContentOK = Set-ContentError -Index $RowIndex -Column $Column -Value $Row.$Column

If (-not $ContentOK) {
	Throw "The csv content is incorrect!"

Open in new window

A sample csv:
"DoeJohn", "John Doe"
"DoeJohn", "John'Doe"
"DoeJane12345678901234", "Jane Doe"

Open in new window


Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Here's a look at newsworthy articles and community happenings during the last month.
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question