How you can log EWS Traces to a file in PowerShell

How you can log EWS Traces to a file in PowerShell In case your utilizing the EWS Managed API in your PowerShell scripts and you should do some prolonged debugging to work out why a script is not working the way in which you anticipate in sure environments you are able to do this by utilizing Tracing as described in . What this does as soon as it’s enabled is it outputs all of the requests and responses which might be despatched to and from the Change server so you possibly can see precisely what’s happening and probably extra info on specific errors which might be occurring.  So in a EWS Managed API script to allow this you simply have to set the TraceEnabled property on the ExchangeService object to true eg

$server.TraceEnabled = $true

And you’ll then begin seeing traces like the next within the console

A a lot cleaner means of capturing these traces is to configure the EWS Managed API to make use of a separate log file to log them to a file so you possibly can overview them later. To do that it requires that you just create a category that implements an Interface of ITraceListener .  In C# this a reasonably trivial factor to do however in PowerShell its a little bit extra difficult. Nonetheless utilizing Add-Kind in PowerShell provides you the flexibility to easily outline your personal customized class that implements the interface after which compile this on the go which then makes it obtainable in your PS Session. The fundamental steps are

  • You might want to outline an class that implements the interface (by way of inheritance) and the strategies outlined in that interface on this case it solely has one known as Hint
  • Outline your personal code to carry out the underlying logging in my instance its a easy one liner that can append the Tracemessage to a File the trail of which is held within the Public Property I’ve outlined in my class 
  • Use Add-Kind to compile the category and make it obtainable in your PS Session
  • Create a Occasion of the Class you simply outlined eg this is a perform to do it
perform TraceHandler(){
$sourceCode = @"
    public class ewsTraceListener : Microsoft.Change.WebServices.Knowledge.ITraceListener
        public System.String LogFile {get;set;}
        public void Hint(System.String traceType, System.String traceMessage)
            System.IO.File.AppendAllText(this.LogFile, traceMessage);

Add-Kind -TypeDefinition $sourceCode -Language CSharp -ReferencedAssemblies $Script:EWSDLL
$TraceListener = New-Object ewsTraceListener
return $TraceListener


Then in your PS Code simply use the Occasion (Object) of the Class you simply created (first setting the LogFile property to path of the File you need to log to) eg

        $service.TraceEnabled = $true
$TraceHandlerObj = TraceHandler
$TraceHandlerObj .LogFile = "c:Tracing$MailboxName.log"
$service.TraceListener = $TraceHandlerObj

Leave a Reply