This is part 3…if you haven’t read part 1 or part 2 you probably want to go back and read those.
Now that we’re all up to speed, I promised I’d talk about drawing shapes in Visio.
We’ll start with an easy one.
Drawing Circles and Rectangles
Remember that you have to open Visio with PowerShell in order to access it from a script.
$Visio= New-Object -ComObject Visio.Application
We can open a new (blank) document using the same technique we saw last time to open a document, except we will pass an empty string:
$Doc=$Visio.Documents.Add('')
Now, we can get a reference to the active (only) page in the document by accessing the ActivePage property of $Visio. We could also have looked at the Pages collection on $Doc and referenced it either by ID (1) or name (Page-1)
$Page=$Visio.ActivePage #Or #$Page=$Doc.Pages(1) #$Page=$Doc.Pages('Page-1')
Now that we’ve got a page, let’s see what Draw methods we have:
$Page | get-member Draw*
DrawOval and DrawRectangle sound pretty straightforward. Let’s try them:
$Page.DrawRectangle(1,1,5,5) $Page.DrawOval(6,6,8,8)
Here’s what it looks like in Visio (note that my diagrams are using US measurements, so the numbers correspond to inches):
The functions also returned the objects that were drawn to the console (which we could have saved in variables if we were paying attention).
Drawing Shapes
Notice that there weren’t any methods for drawing shapes, which is what you really want to do in Visio. Shapes in Visio are stored in what Visio calls stencils, and are typically separate files. To open a stencil and not show it in Visio you can use the OpenEx method of the application object (which we are calling $Visio) and pass the filename and the constant 64 (which means “open hidden”). Here, I’m opening a stencil which contains a bunch of shapes for different kinds of servers. The _U at the end of the filename means that it uses US measurements rather than metric.
$stencilPath='C:\Program Files (x86)\Microsoft Office\Office15\Visio Content\1033\SERVER_U.VSSX' $stencil=$Visio.Documents.OpenEx($stencilPath,64)
I’ve stored the loaded stencil in a variable because we want to work with it.
The shapes in the stencil are stored in a collection called Masters.
Let’s put an FTP Server somewhere on the page:
$Master=$stencil.Masters('FTP Server') $Page.Drop($Master,4,4)
That’s enough for today. Next time we’ll think about connecting objects together.
Let me know what you think in the comments!
–Mike