Forum Discussion
cimpercee
Mar 06, 2023Copper Contributor
Unable to catch the error
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...
Mar 07, 2023
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
- cimperceeMar 07, 2023Copper ContributorI will try your suggestion, thanks
- Mar 08, 2023Let us know if it works out!
- cimperceeMar 09, 2023Copper ContributorI 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}
}