[NoBrainer] Automating Sparx Enterprise Architect with PowerShell

It has been some time since I have last posted something on our blog, so I will start with something easy: today I made the switch from Sparx Enterprise Architect v13.5 to v14.0. And yes, it really paid off since I now can actually decipher all those small connector icons on my Surface Book 2 screen which has a resolution of more than 3000px horizontally …

While I was at it I needed to extract a couple of diagrams from a model so I decided to give PowerShell a try and have it automated for me. As it turned out it was quite easy (except for a few things – more on that later).

In EA it all starts with the Object Model which shows you roughly how to get started in C#, Java and some script languages. EA being exposed as an ActiveX COM object for PowerShell loading a repository looks like this:

A repository is also a COM object, so inspecting types is a little bit harder as usual, as all you see is: __ComObject. Each repository has a collection of Models which in turn contain a Packages collection. In each Package you find a Diagrams collection which may hold zero or more diagrams.

Exporting a diagram is limited to PDF, PNG, JPG and EMF via $diagram.SaveAsPDF() and $diagram.SaveImagePage(). The documentation is sparse but enough to start. A speciality with images is that you have to export an image for each page of the diagram whereas with PDF the whole diagram is exported.
This means you have to check on every diagram of how many pages it consists and save them with separate calls:

A downside while exporting images is, that every image has always the size of a full page – regardless its actual size, as you can see in the following image (notice all the white space at the bottom):

Exported via PowerShell

Note: see the comment at the end of the post on how this can be worked around.

Summary

Automating EA is easy, but the API has a very weak documentation and lacks good samples. Methods are only partially documented and you have to try and error a lot. Doing this in C# does not make things easier as there you have to use the same COM interop library. At least automation is possible …

Make sure to close the file and call Exit() on the repository, otherwise you have leftover EA processes in your system.

Comments

Thanks a lot for this useful example of enumerating all diagrams – just what I need.
About the “page-by-page” issue of exporting to images : this can be circumvented by using the PutDiagramImageToFile() function of the EA Project class: