Tuesday, August 10, 2010

powershell - parse .csv file

Powershell is ideal for bulk operations, e.g. creating lots of users in active directory.

Say we have a .csv file that looks like this:

loginname;firstname;middlename;lastname;fullname;function;password
f.deboer;f;de;boer;Boer, de, Frank;teacher;mypass$78
r.deboer;r;de;boer;Boer, de, Ronald;teacher;123pass60
m.manager;m;;manager;Manager, Mike;manager;superpassw0rd

You might want to specify some global variables first.

$import_file="d:\import\importfile.csv"

Now let’s create a simple function to read the file.

function readcsvfile()
{
  $UserDetails=Import-Csv -delimiter ";" $import_file
  foreach($UD in $UserDetails)
  {
    $loginname=$UD.loginname
    $firstname=$UD.firstname
    $middlename=$UD.middlename
    $lastname=$UD.lastname
    $fullname=$UD.fullname
    $function=$UD.function
    $password=$UD.password

    echo "$username"
    echo "$password"
    # or something else you want to do with tis information
  }
}