I have powershell script which does some AD operations from CSV file which has below data with headers

SamAccountname,country,name

I need the script to stop executing and send email if any of the column data is empty. I tried the below code but it exists even if all fields have data. Any help will be appreciated.

$import=Import-Csv $import_file -Encoding Unicode

if ($import)

{

write-host "user list was successfully imported."

}
else

{write-host "No user in the file imported.The script will now exit";Start-Sleep -Seconds 10; exit}

foreach ($userlist in $import)
{
    
    if ( $null -eq $userlist.SamAccountName -or $null -eq $userlist.country -or $null -eq $userlist.name) {
        
        
        Write-host "The csv has correct data"
        }
        else {
    Write-Host "CSV Empty Field!"
    send-MailMessage -From $sender -To $recipients -Subject "ALERT  Script Failed" -Body "The  script has failed due to empty columns please validate the csv file" -SmtpServer 'mailserver'    
    exit;
        }
}
4 Spice ups

It looks like you have it written that if $Null equals any of those fields, it will write " The csv has correct data". You either need to reverse those two or change it to Not Equal (-NE)

1 Spice up

Gorfmaster has stated your problem correctly. However, you can ignore problematic records if you want and continue. I wasn’t sure of your use case so just throwing it out there.

You could check for the empty data and if found, alert someone then still proceed with the ones that are complete records.

it’s not necessary $Null, it could be an empty string or whitespace

you can try something like so

if ($userlist.SamAccountName -and $userlist.country -and $userlist.name)

or if you want to be more specific

[string]::IsNullOrEmpty()
2 Spice ups

Thanks.

I do not want the script to continue if there is any empty field or spaces in any of the column. The script should not perform any action of any of the columns even if single empty field in any of the field.

I updated script below still it does exit.

if ( $null -NE $userlist.SamAccountName -or $null -NE $userlist.country -or $null -NE $userlist.name)
foreach($row in $csv){
    write-verbose $row -verbose

    if ($row.SamAccountName -and $row.country -and $row.name) {
        Write-host "The csv has correct data"
    }
    else{
        "STOP"
    }
}
VERBOSE: @{SamAccountname=; country=US; name=Mike}
STOP
VERBOSE: @{SamAccountname=bob; country=DE; name=Mark}
The csv has correct data
1 Spice up

If you go that route, you have to use AND instead of OR because you are saying if any one of the fields is not equal to null then proceed(which is not what you want).

1 Spice up

@ Neally : It worked now however one dumb question if we have not mentioned any Null value to compare how does it work?

PowerShell automagically evaluates for some conditions