Home > Uncategorized > Powershell: Code snippet of the day

Powershell: Code snippet of the day

Powershell supports background jobs. Related commandlets are:

  • Start-Job
  • Stop-Job
  • Wait-Job
  • Get-Job
  • Recieve-Job

which by the way can be listed directly by “get-command *job*”. Todays code snippet uses a background job to simulate a growing log file:

# simulate incremental log file growth
start-job -initializationScript {
  new-item -force -type file c:\temp\logfile.txt
} -scriptblock {
    $count = 0
    while ($count -lt 100)
    {
        add-content c:\temp\logfile.txt "line $count"
        [System.Threading.Thread]::Sleep(1000)
        $count ++
    }
}

We can use the get-content command to incrementally update (tail) the result:

# tail file
get-content c:\temp\logfile.txtwait

Note: For some reason the “Tail-File –Wait” command from Powershell community extensions fails. It seems to lock the file, preventing the background job from updating it. Strange.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: