During last week's PowerShell class, several students wanted to know if they could manipulate Excel files the same way that they used to do in VBScript. Of course! In fact, the syntax is almost identical, because PowerShell can use the same COM object that you used in VBScript. One student, Sam Hays, was kind enough to share this brief example of how to do it:
Line 1 starts the process by instantiating the COM object - note that Excel must be installed in order for this to work. Lines 5 and 6 create a new workbook (XLS file) and add a spreadsheet to that workbook.
Lines 8-10 put some text in three cells across the top of the page. Note the (row,column) references, and that rows and columns start counting from 1, not zero. Line 12 sets a counter variable to 2, which is the row that we'll start putting data in.
Line 14 retrieves PowerShell processes using Get-Process.
Lines 16-22 run through those processes and put process information into the spreadsheet. You'll notice on line 21 that the counter is incremented, so that each subsequent process goes on a new line.
Now, I do have to point out that for such a simple example, there's a much easier way:
I know, it's not an XLS file, but if you double-click it, it'll look pretty much the same, won't it? If you need to get more complex, then manipulating Excel directly by means of its COM object is a good solution.