SuperDOS
SuperDOS

Reputation: 331

Check ADusers for property export-csv and include null

I have a list of mobile numbers that I want to try to match ad users with and then export as csv.

The current script works so far but I want it to include a row when it doesn't find a user which says the mobile number that it had no match from.

$ou="OU=User Accounts,OU=Users,OU=Company,DC=dc01,DC=local"

get-content chk_usr_mobile.csv | 
ForEach {
$aduser=get-aduser -SearchBase $ou -filter{(mobile -eq $_)} -Properties *|
select -Property company,emailaddress,@{L='departmentnumber'; E={$_.departmentnumber[0]}}, mobile,givenname,sn
if ($aduser -eq $null){
$aduser=$_
}
else{
$aduser}
} | export-csv .\tel_result.csv -encoding UTF8 -notypeinformation 

So the ouput I want should be like this in the csv:

"company","emailaddress","departmentnumber","mobile","givenname","sn"
"Company","[email protected]","123","123456789","Joe","Doe"
"no user found for number 98765431"
"Company","[email protected]","124","456789123","Jane","Doe"

Upvotes: 0

Views: 229

Answers (1)

Theo
Theo

Reputation: 61028

Judging from your code, the input CSV file isn't a CSV file at all, but rather a text file with phone numbers each on a separate line..

In order to not break the output CSV, I suggest you do the following:

$ou="OU=User Accounts,OU=Users,OU=Company,DC=dc01,DC=local"
Get-Content chk_usr_mobile.csv | ForEach-Object {
    $aduser = Get-ADUser -SearchBase $ou -Filter { mobile -eq $_ } -Properties Company,EmailAddress,departmentnumber,Mobile,GivenName,Surname
    if ($aduser) {
        $aduser | Select-Object Company,EmailAddress,@{L='DepartmentNumber'; E={$_.departmentnumber[0]}},Mobile,GivenName,Surname
    }
    else {
        [PSCustomObject]@{
            Company = 'no user found for number {0}' -f $_
            EmailAddress = ''
            DepartmentNumber = ''
            Mobile = ''
            GivenName = ''
            Surname = ''
        }
    }
} | Export-Csv .\tel_result.csv -Encoding UTF8 -NoTypeInformation -Force

Upvotes: 1

Related Questions