Unable to catch the error

Copper Contributor

I am trying to query a user and was hoping to build a csv file for those that I can and cannot get. I'm not really sure why.

 

 

users = import-csv ".\OU.csv" -Delimiter ";"
    foreach ($user in $users) {
    $O365user = Get-ADUser -SearchBase $user.ou -Properties * -Filter * | ? {$_.admindescription -eq $null -and $_.emailaddress -ne $null} | select EmailAddress,SamaccountName
                              }
    foreach ($User in $O365user){ 
   try {
        $dUser = Get-mailbox $user.emailaddress -ErrorAction Stop
    }
    catch {
        if ($_ -like "*The operation couldn't be performed because object*") {
            "User '$u' does not exist."
        }
        else {
            "An error occurred: $_"
        }
        continue
    }
    "User '$($user.displayname)' exists."
    # Do stuff with $ADUser

}

 

 

7 Replies
It looks like you're trying to query a list of users from a CSV file and then check if they have an Office 365 mailbox. The script seems to be missing the part where you write the results to a CSV file.

To write the results to a CSV file, you can use the Export-CSV cmdlet. Here's an updated version of your script that writes the results to a CSV file:

$users = import-csv ".\OU.csv" -Delimiter ";"
$results = @()
foreach ($user in $users) {
$O365user = Get-ADUser -SearchBase $user.ou -Properties * -Filter * | ? {$_.admindescription -eq $null -and $_.emailaddress -ne $null} | select EmailAddress,SamaccountName
foreach ($User in $O365user){
try {
$dUser = Get-mailbox $user.emailaddress -ErrorAction Stop
$result = [PSCustomObject]@{
DisplayName = $user.displayname
EmailAddress = $user.emailaddress
Status = "Exists"
}
$results += $result
}
catch {
if ($_ -like "*The operation couldn't be performed because object*") {
$result = [PSCustomObject]@{
DisplayName = $user.displayname
EmailAddress = $user.emailaddress
Status = "Does not exist"
}
$results += $result
}
else {
"An error occurred: $_"
}
continue
}
}
}
$results | Export-Csv -Path ".\Results.csv" -NoTypeInformation


This script creates an empty array $results and then adds a custom object to it for each user that is found. The custom object contains the user's display name, email address, and status (either "Exists" or "Does not exist").

At the end of the script, the results are exported to a CSV file using the Export-Csv cmdlet. The -NoTypeInformation parameter is used to exclude the object type information from the CSV file.

@cimpercee I think this should work:

 

users = import-csv ".\OU.csv" -Delimiter ";"
    foreach ($user in $users) {
    $O365user = Get-ADUser -SearchBase $user.ou -Properties * -Filter * | ? {$_.admindescription -eq $null -and $_.emailaddress -ne $null} | select EmailAddress,SamaccountName
                              }
    foreach ($User in $O365user){ 
   try {
        $dUser = Get-mailbox $user.emailaddress -ErrorAction Stop
        $dUser | export-csv -path c:\data\users.csv -NoTypeInformation -Delimiter ';' -Encoding UTF8 -Append 
    }
    catch {
            "User '$u' does not exist."
}

 

If the user can be found, it exports the data to a CSV file and appends it for every user. It the user can't be found, it will just write that it can't be found and continue processing

I did cut the rest of the code because for this query, I can't even catch the error. thanks. I will try your suggestion
I will try your suggestion, thanks
Let us know if it works out!
I did try it, to get some idea how you would code it by combining it with my own code. I didn't manage to get it work. error is still not handled properly.

$users = import-csv ".\OU.csv" -Delimiter ";"
foreach ($user in $users) {
$O365users = Get-ADUser -SearchBase $user.ou -Properties * -Filter * | ? {$_.admindescription -eq $null -and $_.emailaddress -ne $null} | select EmailAddress,SamaccountName
}
foreach ($o365user in $o365users){
Try{
$user = get-mailbox $o365user.emailaddress | Select AccountDisabled,RecipientTypeDetails,primarysmtpaddress,userprincipalname,displayname,alias -errorAction Stop

if ($user.accountdisabled -eq $true -and $user.recipientTypedetails -eq "usermailbox"){
$staleusers += [PSCustomObject]@{
"Emailaddress" = $user.primarysmtpAddress
"Name" = $user.displayname
"UPN" = $user.userprincipalname
"Status" = $user.accountdisabled
"RecipientType" = $user.recipienttype}
}}
Catch{
"User $o365user.emailaddress does not exist"}
}
$StaleUsers | Export-Csv .\staleusers1.csv -notypeinformation
#$nonexistentusers |where {$_.| export-csv .\nonexistentusers.csv

foreach ($users in Staleusers){
get-aduser -properties * -filter * | ? {$_.emailaddress -eq $staleusers.emailaddress}
}

 It looks like there are a couple of issues with the code you provided.

Firstly, there's a typo in the variable name in the foreach loop that tries to access the $o365users variable. The variable is named $O365users (capital "O"), so you need to use that instead.

Secondly, the foreach loop that tries to get the corresponding AD user for each stale Office 365 user is not assigning the result to a variable, so it's not doing anything with the output. You should assign the result to a variable, like $aduser, and then do something with that variable

 

 

Here's the modified code that should work:

 

 

 

 

$users = import-csv ".\OU.csv" -Delimiter ";"
$staleusers = @()

foreach ($user in $users) {
    $O365users = Get-ADUser -SearchBase $user.ou -Properties * -Filter * | ? {$_.admindescription -eq $null -and $_.emailaddress -ne $null} | select EmailAddress,SamaccountName
}

foreach ($o365user in $O365users){
    Try{
        $user = get-mailbox $o365user.emailaddress | Select AccountDisabled,RecipientTypeDetails,primarysmtpaddress,userprincipalname,displayname,alias -errorAction Stop

        if ($user.accountdisabled -eq $true -and $user.recipientTypedetails -eq "usermailbox"){
            $staleusers += [PSCustomObject]@{
                "Emailaddress" = $user.primarysmtpAddress
                "Name" = $user.displayname
                "UPN" = $user.userprincipalname
                "Status" = $user.accountdisabled
                "RecipientType" = $user.recipienttype
            }
        }
    }
    Catch{
        "User $o365user.emailaddress does not exist"
    }
}

$StaleUsers | Export-Csv .\staleusers1.csv -notypeinformation

foreach ($staleuser in $staleusers){
    $aduser = get-aduser -properties * -filter * | ? {$_.emailaddress -eq $staleuser.emailaddress}
    # do something with $aduser, e.g. output its properties
    $aduser
}

 

 

 

Note that I added a $staleusers variable to collect the stale Office 365 users, which is then exported to a CSV file. I also added a foreach loop to get the corresponding AD user for each stale user, which assigns the result to the $aduser variable and outputs its properties. You'll need to replace # do something with $aduser with whatever code you want to execute for each AD user.

 

Edit#  I didnt Corrected the typo in the modified script, 

 

 

@cimpercee