PowerShell Out-GridView–A cmdlet with benefits

July 15, 2011

in Microsoft,NLog,PowerShell,Reactive Extensions,Reactive Framework,UNIX

A question I often get about PowerShell from ex-UNIX developers is whether or not PowerShell can “tail” files. Unfortunately, there is no direct analogy to the tail command in PowerShell. It’s typically used to watch the contents of a log file live as it is added to, and that is certainly something that PowerShell can do.

This question comes from a developer who is using NLog to log messages from his app involving Reactive Framework code.

Get-Content –Wait C:\Test.txt

Get-Content is a PowerShell cmdlet (aliased to type (for DOS people) and cat (for Unix people)). It gets the content of the item at the location specified by the path, such as the text in a file. imageIt reads the content one line at a time and returns a collection of objects, each of which represents a line of content.

The –Wait parameter waits for content to be appended to the file. If content is appended, it returns the appended content.

Out-GridView

You can pipe the results of PowerShell to a grid view window where the output is displayed in an interactive table. Out-GridView is available out of the box.

Features of Out-GridView

  • Hide, Show, and Reorder Columns
  • Sort
  • Quick Filter
  • Criteria Filter
  • Copy and paste

How To

Get-Content –Wait c:\test.txt | Out-GridView. As the data is updated from the background task (see code below), another line is added to the table. You can even do a quick filter and as the lines are appended to the file, Out-GridView adds them applies the filter to the new information.

image

Try It Out

del C:\test.txt            

Start-Job -ScriptBlock {
    "Time,Message" | Add-Content c:\test.txt
    while($true) {
        "Testa", "Testb","Testc","Testd" | Get-Random | % {
            "{0},{1}" -f (Get-Date).ToString(), $_
        } | Add-Content c:\test.txt
        Start-Sleep -Milliseconds 1500
    }
}            

sleep 2
Get-Content c:\test.txt -wait |  ConvertFrom-Csv | Out-GridView

{ 2 comments… read them below or add one }

Chad Miller 07.15.11 at 9:27 am

Out-GridView is an underestimated cmdlet. I’ll use the copy/paste feature to move data if I’m doing a one off task with small number of rows. It’s easy way to get data into Excel, Access or SQL Server…

Excel
GridView -> Ctrl+A -> Open Excel speadsheet -> Ctrl+V

SQL Server
GridView -> Ctrl+A -> Open SSMS -> Select Table in Object Explorer -> Edit Top 200 Rows + Ctrl+V

Doug Finke 07.15.11 at 1:33 pm

That’s a great tip too Chad. Thanks.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Contrat Creative Commons

© 2007-2012, Doug Finke