Author Posts

August 24, 2017 at 10:10 pm


I have this code I want to run in Azure:

$users = import-csv c:\Users.csv
foreach ($user in $Users) {Get-Mailbox $user.samAccountName -Credential $creds }

and I expect errors but how do I also log them to a text file, please? If it can simply return "mailbox does not exist" and "mailbox exists", instead of many lines of error per object queried, all the better.


August 25, 2017 at 2:00 am

I wouldn't suggest just returning something like "mailbox doesn't exist" because when a mailbox can't be found, it gives an error that says the object couldn't be found on a specific GC. Most likely it's because the mailbox object doesn't exist, but it also could be due to replication issues in the AD environment, or some issue with that specific GC. Instead, if you don't want the entire error dumped into a file, you can grab part of it. For example you could do something like the following. Note that the screen will show the list of mailbox objects it did find. Also, I put code in that also logged a "mailbox found" type message to the same log file as the errors. Hope this helps.

$Date = Get-Date -Format yyyyMMdd
$Log = "C:\data\GetMbxResults_$Date.txt"
$Users = Import-Csv -Path C:\data\samaccts.txt
ForEach($User in $Users)
    Get-Mailbox $User.SamAccountName -ErrorAction Stop -Credentials $creds
    #You can have the following two lines if you want to output the successes to the log file.
    $SuccessMsg = "$(Get-Date): [INFORMATION]: Mailbox for $($User.SamAccountName) exists."
    $SuccessMsg | Out-File -FilePath $Log -Append
    $ErrorMsg = "$(Get-Date): [ERROR]: $($_.Exception.Message)"
    $ErrorMsg | Out-File -FilePath $Log -Append

August 25, 2017 at 2:04 am

Added the -Credentials $creds into the example to match the original code you listed.

August 25, 2017 at 11:17 pm

Thanks Kevyn, I will test this next week