#PSTip How to quickly open output file

Note: This tip requires PowerShell 2.0 or above.

When you work interactively with PowerShell, you don’t want to type too much. You want to use aliases, positional parameters, redirection operators, automatic variables… You just want to type as little as possible. 🙂

Let’s start with the fully typed command. The command selects three properties of the process objects, converts output to a HTML page, and sends the resulting HTML page to the c:\temp\process.html file. You also specify a nice title for the HTML page.

PS> Get-Process | ConvertTo-Html -Property Name,Path,Company -Title "Process Information" | Out-File -FilePath c:\temp\process.html

How can you make this command shorter? You can use gps (or even ps) alias instead of the Get-Process cmdlet, omit ConvertTo-Html’s -Property parameter (it’s a positional parameter), and use the redirection operator (>) instead of the Out-File cmdlet.

PS> gps | ConvertTo-Html Name,Path,Company -Title "Process Information" > c:\temp\process.html

You have your HTML file now, but you also want to open it in the default browser and check the result. The following command might look cryptic, but I’m sure you will use it all the time after you finish reading this tip.

PS> ii $$

That command’s opened the c:\temp\process.html file in the default browser, right? The magic of PowerShell. Why does that command work? ii is the alias for the Invoke-Item cmdlet, but the real power lies in the $$ automatic variable. $$ automatic variable contains the last token in the last line received by the session, and in this case that’s c:\temp\process.html.
By the way, start, the alias of the Start-Process cmdlet, comes in handy for this task as well.

PS> start c:\temp\process.html

That’s short and easy to understand. However, as you have seen, you can do it better.

Filed in: Columns, Tips and Tricks Tags: ,

One Response to "#PSTip How to quickly open output file"

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: