Using PowerShell, it is easy enough to create, say, an instance of the Excel Application class and start manipulating it:
$app = New-Object -ComObject "Excel.Application"
However, if I need to use the constants like xlDoubleQuote or xlDelimited - it seems like I am forced to hard code them. I would really like to be able to do something like:
$constants = New-Object -ComObject "Excel.Constants"
$constants.xlDoubleQuote
And see that it would return the value of 1. Unfortunately I can't create an instance of an enumeration, and there doesn't seem to be a way to reference it like you would a normal .NET class library:
[Excel.Constants]::xlDoubleQuote
Is there some way to dynamically import that enumeration into PowerShell? Maybe through the managed libraries rather than COM?
Keith already gave you the answer, here's another option. You can use tab completion on the $xlConstants object to get the constants:
Using Visio 2016 32-bit, I found that attempting to use Keith Hill's approach resulted in error message: "Add-Type : Cannot add type. The assembly 'Microsoft.Office.Interop.Visio' could not be found." Shay Levy's approach required a bit more modification to work with Visio. Here is what I was able to get working:
Disappointingly, it takes around 12 seconds to execute when I tested.
To combine the technique from Keith Hill's helpful answer with the tab-completion idea from Shay Levy's answer:
Note: To find the full name of the
Constants
type, you can use tab completion: after having runNew-Object -ComObject Excel.Application
, type[constants<tab>
(don't type the closing]
), which should expand to[Microsoft.Office.Interop.Excel.Constants
; if a type from a namespace other thanMicrosoft.Office.Interop.Excel
shows up, press the tab key until the desired type is found.Now you can:
Access the individual enumeration values as static members of the type stored in
$xlConstants
, via the::
operator, which also works with tab completion; e.g.:Get a specific value's underlying number by either casting to
[int]
or accessing the.Value__
property:Enumerate all symbolic names:
Also show the numbers underlying the symbolic names:
Use the primary interop assembly for Excel. If you have Office installed these should be in the GAC. Use like so:
Keith and Shay gave perfect answers, however, note this:
When using Excel 2003 or Excel 2007, the Office Primary Interop Assemblies (PIAs) should be installed on the machine. There are redistributable versions available from Microsoft. See this stackoverflow.com posting here for more info:
Different Interop references on two different computers doesn't work