Chapter 10. PowerShell, COM, and More

I bet almost every application you work with sports the option “Export to Excel.” Good news: PowerShell too provides an easy path to interacting with Microsoft Office, via COM (Component Object Model). In this chapter, I’ll show you how to “control” both Excel and Internet Explorer through a COM interface. Master this technique, and you’ll find yourself leveraging it over and over. It provides quick solutions for your users, and soon you’ll be using it in your day-to-day routines in ways you never expected.

Before I go down the COM route, I want to show you how you can use Invoke-Item to great effect.

Opening a File in Excel Using Invoke-Item

I have a file named authors.csv, the contents of which are shown in Figure 10-1. If I pass that filename to Invoke-Item, it will perform the default action for the file’s extension on the specified item. Typing the following will launch Microsoft Excel and open authors.csv; see Figure 10-2.

PS C:\> Invoke-Item .\authors.csv
Authors.csv file content

Figure 10-1. Authors.csv file content

Launching Excel with Invoke-Item

Figure 10-2. Launching Excel with Invoke-Item

Note

The Invoke-Item cmdlet is aliased to ii. Try the following:

PS C:\> ii .

This will launch the Windows file explorer in the current directory.

The return on investment (ROI) on these three ...

Get Windows PowerShell for Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.