Search code examples
csvpowershellif-statementtry-catchcustom-error-handling

Powershell: How to throw an error if a CSV entry is blank


I've written an extensive script that runs through an AD termination process, and the script can obtain the necessary information from a CSV. How do I make it so that it errors out if the entry is blank in the CSV? I've tried putting in Try-Catch, If-Else, everything that I know how to do. I've tried changing the error action, and I can get it to throw system generated errors (ex. "Cannot bind parameter "Identity" to the target..."), but I cannot get it to do what I want. Please see the code example below:

(Yes, I know that I'm duplicating values. This of importance later on in the script, and not the part I'm having issues with)

    $owner = $user.'Network User ID'}
    $loginID = $user.'Network User ID'
    $Identity = Get-ADUser -Identity $owner -Properties Displayname |Select-Object -ExpandProperty Displayname 
    $manager = $user.'Provide Inbox Access To'
    $NewOwner = $user.'Provide users email group ownership to'
    $NewOwnerID = $User.'Provide users email group ownership To'

What I need it to do is throw an error if ANY entry in the CSV is blank, and terminate. The most promising idea that I tried was:

    If ($Owner -eq $Null)
    {
    Write-Host "Invalid entry, the Network User ID field cannot be blank"
    Write-Host "Press Enter to Exit..."
    Exit
    }
    Else
    {
    #Do everything else
    }

But even that still fails.

In summary, what I need to do is throw a custom terminating error if an entry in the CSV is blank.

Any help is greatly appreciated!

EDIT

If this helps, here is more of the real code...

$Confirmation = Read-Host "Please double check the information in the file. Are you sure you want to continue? (Y/N)"

If($Confirmation -eq "Y")
{
Write-Host "You have chosen to proceed. Processing Termination" -BackgroundColor DarkCyan
#Import file
$file = "C:\TerminateUsers.csv"
$data = Import-Csv $file
#Set disabled OU
$disabledOU = "OU=Users,OU=Disabled Accounts, OU=Corporate"

$colOutput = @()
foreach ($user in $data)
{
    #Grab variables from CSV
    $owner = $user.'Terminated Network User ID'}
    $loginID = $user.'Terminated Network User ID'

    #Displayname required for Outlook functions
    $Identity = Get-ADUser -Identity $owner -Properties Displayname |Select-Object -ExpandProperty Displayname 
    $manager = $user.'Provide Inbox Access To'
    $NewOwner = $user.'Provide users email group ownership to'
    $NewOwnerID = $User.'Provide users email group ownership To'
    If (Get-ADUser -LDAPFilter "(sAMAccountName=$loginID)")
        {
        $date = Get-Date -Format d
        #Disable account, change description, disable dialin, remove group memberships
        Set-ADUser -Identity $loginID -Enabled $false
        Set-ADUser -Identity $loginID -Replace @{Description = "Terminated $date"}
        Set-ADUser -Identity $loginID -Replace @{msNPAllowDialin = $False}
        RemoveMemberships $loginID 

This isn't all of it, but this is the part we're working with...


Solution

  • There's a number of issues you're going to run into here.

    First, $Owner -eq $Null isn't going to do what you likely want to do. Mainly, the issue is that an empty string is not a null value. They're different. Instead, your test should be:

    if ([string]::IsNullOrEmpty($owner)) { ... }
    

    Or:

    if ([string]::IsNullOrWhiteSpace($owner)) { ... }
    

    This second one returns true if the string includes only tabs, spaces, or other whitespace characters, or is an empty string, or is null.

    Second, to throw an exception, you need to use the throw keyword. See Get-Help about_Throw. For example:

    if ([string]::IsNullOrWhiteSpace($owner)) {
        throw "Owner is null or empty.";
    }
    

    If you have this embedded in a try block, you can catch the exception with the associated catch blocks. See Get-Help about_Try_Catch_Finally. You can also use Trap, I believe (See Get-Help about_Trap).

    Finally, the default action when an error is encountered is controlled by the $ErrorActionPreference variable. That variable's default value is Continue, so error messages will be displayed but the script will continue executing as though no error happened at all. I'm not entirely sure how this works with manually thrown exceptions and try/catch blocks, but unless I know that I want my script to ignore errors, I start just about every script with:

    $ErrorActionPreference = Stop;
    

    See Get-Help about_Preference_Variables and Get-Help about_CommonParameters for more about this one.