Powershell script to check attribute values are present in each line of csv

Freddie 21 Reputation points
2022-09-20T16:31:43.617+00:00

I am writing a Powershell script that generates username based on first and last name. I will be giving input csv which has various columns like first name, lastname, manager name, start date etc.
The script should check for mandatory attribute like first name, lastname, manager name, start date etc. for each user in csv, and if any of the mandatory attribute is missing for a particular user, that record should be skipped, and move to next line. And also, generate a different error file for all the skipped records with a reason like firstname is missing, managername is missing.

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,399 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 49,071 Reputation points
    2022-09-20T17:42:20.817+00:00

    Try using Import-Csv to read the CSV file. The result is a table that you can use the Where-Object on to filter out rows that are missing values in the columns that you require.

    0 comments No comments

  2. Andreas Baumgarten 98,531 Reputation points MVP
    2022-09-20T17:45:20.88+00:00

    Hi @Freddie ,

    maybe this helps to get started:

    CSV test file content:

    firstname,lastname,manager,description  
    paul,miller,mickeymouse,something  
    ,smith,paul,something  
    peter,,someone,something  
    Lucie,Meyers,,something  
    Kerry,Longy,Peter,  
    

    Script (assuming firstname, lastname and manager`` must be present. description` is optional):

    Import-Csv -Path "Junk\checkvalue.csv" | ForEach-Object {  
        if (!$_.firstname -or !$_.lastname -or !$_.manager) {  
            Write-Output "some mandatory details are missing $_ "  
            Export-Csv -Path "Junk\checkvalue_missingdetails.csv" -InputObject $_ -Append -NoTypeInformation  
        }  
        else {  
            Write-Output "line contains all mandatory details ... do something"  
        }  
    }  
    

    ----------

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten