Поделиться через


Using the ConvertTo-Html Cmdlet

Saving Data as an HTML File

No offense to the console window or a text file, but sometimes it’s hard to beat HTML as an output device (for one thing, HTML gives you more formatting options and flexibility). Fortunately the ConvertTo-Html cmdlet makes it very easy to view Windows PowerShell output in a Web page. For example, this command uses the Get-Process cmdlet to retrieve information about all the processes running on the computer. The output from Get-Process is piped to the ConvertTo-Html cmdlet, which creates an HTML table out of that data. In turn, that table is piped to the Set-Content cmdlet, which saves the information as a Web page (C:\Scripts\Test.htm). That sounds like a lot of work, yet the command is as simple as this:

Get-Process | ConvertTo-Html | Set-Content c:\scripts\test.htm

The resulting Web page looks something like this:

Good point: the table is a bit unwieldy; that’s because the large number of properties returned by Get-Process results in a corresponding large number of columns in the table. This revised command limits the properties displayed in the table to Name, Path, and FileVersion:

Get-Process | ConvertTo-Html name,path,fileversion | Set-Content c:\scripts\test.htm

Our simplified Web page looks like this:

Much better.

But not perfect. By default the title assigned to the Web page is the less-than-scintillating HTML Table. With that in mind, this command uses the -title parameter to change the window title to Process Information:

Get-Process | ConvertTo-Html name,path,fileversion -title "Process Information" | Set-Content c:\scripts\test.htm

We’re definitely on the right track now.

Let’s do one last thing. As you can see, the only information we have on our Web page is the data table. If you’d like to preface the table with some explanatory information then simply include the -body parameter followed by the text you’d like to appear on the page:

Get-Process | 
ConvertTo-Html name,path,fileversion -title "Process Information" -body "Information about the processes running on the computer." | 
Set-Content c:\scripts\test.htm

Granted, we didn’t add much value here. But at least the resulting Web page gives you a hint of the kinds of things you can do:

We should also point out that information configured using the -body parameter is HTML; that means the parameter can include any valid HTML tags. Want to display your preface using the <H2> style? Then just include the <H2> and </H2> tags:

Get-Process | 
ConvertTo-Html name,path,fileversion -title "Process Information" -body "<H2>Information about the processes running on the computer.</H2>" | 
Set-Content c:\scripts\test.htm

Or, to put it a bit more graphically:

If you’ve ever wondered why the Scripting Guys aren’t Web page designers, well, consider the preceding screenshot Exhibit A. But now that you know how ConvertTo-HTML works you can do better.