Want to create a log file of all output

This topic contains 3 replies, has 2 voices, and was last updated by  Jeff Taylor 1 month ago.

  • Author
    Posts
  • #78036

    Jeff Taylor
    Participant

    Hello,

    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.

    thanks

  • #78043

    Kevyn
    Participant

    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"
    $Error.Clear()
    $Users = Import-Csv -Path C:\data\samaccts.txt
    ForEach($User in $Users)
    {
      Try
      {
        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
      }
      Catch
      {
        $ErrorMsg = "$(Get-Date): [ERROR]: $($_.Exception.Message)"
        $ErrorMsg | Out-File -FilePath $Log -Append
      }
    }
    
    • #78115

      Jeff Taylor
      Participant

      Thanks Kevyn, I will test this next week

  • #78046

    Kevyn
    Participant

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

You must be logged in to reply to this topic.