Find first variable that is not null

I have a csv file that I’m importing data from. Four of the columns potentially contain phone numbers. I am trying to check each one, in order, for a null value. The first one with a value should be used in a variable. I’ve attempted to use an if and elseif to find the correct value. The portion of the code that doesn’t work is below. The variables should be checked in the following order: cel1,cel2,car,home.

If anyone has a better/functional way to do this, I would really appreciate a reply.

#check for phone number
If($user.cel1 -ne $null) {$mobile = $user.cel1}
ElseIf(($user.cel2 -ne $null) -and ($user.cel1 -eq $null)){$mobile = $user.cel2}
elseIf(($user.car -ne $null) -and ($user.cel1 -eq $null) -and ($user.cel2 -eq $null)){$mobile = $user.car}
elseIf(($user.home -ne $null) -and ($user.cel1 -is $null) -and ($user.cel2 -is $null) -and ($user.car -is $null)){$mobile = $user.home}
$mobilephn = $mobile -replace “/” -replace “-”

With the If/ElseIf/Else construct the script will stop trying to evaluate as soon as it finds a “true” condition so you don’t need to keep testing for the previous conditions. Also, if it does read the empty fields in as null, you can just test for the variable, such as:

If ($User.cel1)
{
    $MobilePhn = $User.cel1 -replace "/" -replace "-"
}
ElseIf ($User.cel2)
{
    $MobilePhn = $User.cel2 -replace "/" -replace "-"
}
ElseIf ($User.car)
{
    $MobilePhn = $User.car -replace "/" -replace "-"
}
ElseIf ($User.home)
{
    $MobilePhn = $User.Home -replace "/" -replace "-"
}

Thanks, that seems to be working.

I know I’m a little late in joining the conversation, but wanted to show an alternative way to do it, allowing you to check more columns by adding the column name to the properties array …

Test data:

User,Cel1,Cel2,Car,Home
User 1,555-123-1231,,555-321-1231,
User 2,,555-123-1232,555-321-1232,
User 3,,,555-123-1233,555-321-1233
User 4,,,,555-123-1234
User 5,,555/123/1235,,
User 6,,,555/123/1236,

Sample code:

# Import data
$Data = Import-Csv -Path C:\TEMP\Test.csv -UseCulture

# Specify column names to check for phone number
$Properties = @(
    'cel1',
    'cel2',
    'car',
    'home'
)

# Loop through imported data
foreach ($Record in $Data) {

    # Loop through listed properties
    foreach ($Property in $Properties) {
        $Phone = ($Record."$Property").Trim().Replace('/','-')
        
        # Break out of foreach loop when phone has been found
        if ($Phone) {
            Break
        }
    }
    
    # Output user and phone
    Write-Host "$($Record.User): $Phone"
}

@Christian

That is pretty nifty. I’m going to have to add that to my toolbox!