[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Powershell - check csv format

Posted on 2016-11-15
4
Medium Priority
?
652 Views
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?
0
Comment
Question by:Pete
4 Comments
 
LVL 7

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.
MassUserCreationScriptSource.xls
0
 
LVL 1

Author Comment

by:Pete
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.
0
 
LVL 7

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.
0
 
LVL 85

Accepted Solution

by:
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 = @(
	'SamAccountName',
	'DisplayName'
)
## 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) {
	$RowIndex++
	$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:
"samAccountName","DisplayName"
"DoeJohn", "John Doe"
"DoeJohn", "John'Doe"
"DoeJane12345678901234", "Jane Doe"

Open in new window

0

Featured Post

A Cyber Security RX to Protect Your Organization

Join us on December 13th for a webinar to learn how medical providers can defend against malware with a cyber security "Rx" that supports a healthy technology adoption plan for every healthcare organization.

Question has a verified solution.

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

This process allows computer passwords to be managed and secured without using LAPS. This is an improvement on an existing process, enhanced to store password encrypted, instead of clear-text files within SQL
A walk-through example of how to obtain and apply new DID phone numbers to your cloud PBX enabled users that are configured in Office 365. Whether you have 1, 10 or 100+ users in your tenant, it's quite easy to get them phone-enabled and making/rece…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

872 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