Pages

Thursday, June 17, 2010

Log Retrieval Script

Today's project was to write a script that would retrieve log files using the HTTP protocol.  As I've said in my introductory post, I'm working on teaching myself PowerShell so this seemed like a great task for a script.  There are 24 log files per day so this script will get all 24 log files from the previous day. Here is the code:
# Log Retrevial Script
# Script Constants
$BaseURL = "http://www.example.com/"
$BaseFilePrefix = "fileprefix_"
$Yesterday = Get-Date -format yyyyMMdd ((Get-Date).adddays(-1))
$HourArray = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
$BaseFileSuffix = "-0000.log.gz"
$SavePath = "C:\Log_Downloads\"

$Client = New-Object System.Net.WebClient
Foreach ($Hour in $HourArray)
 {
   if ($Hour -lt 10)
   {
    $File = $BaseFilePrefix + $Yesterday + "0" + $Hour + BaseFileSuffix
   }
  else
   {
   $File = $BaseFilePrefix + $Yesterday + $Hour + $BaseFileSuffix
  }
  $URL = $BaseURL + $File
  $SaveFile = $SavePath + $File
  $Client.DownloadFile($URL, $SaveFile)
  Type $SaveFile
 }

An Introduction to me and this blog

This blog will chronicle my attempts to learn Microsoft's Windows PowerShell. I have over ten years of experience administering Microsoft Windows Server environments. Along the way I have picked up experience with other technologies as well (Linux, Cisco IOS, Cisco VoIP, VMWare - just to name a few).

My day job involves administering many Windows 2008 boxes. In the past, I've done most of my administrative work with minimal scripting. While that isn't a problem with smaller environments, it obviously doesn't scale well. Given that Microsoft seems to be pushing Windows PowerShell as the way to script for their products, that seemed to be the logical tool for me to learn. (I'm not a Microsoft fanboy and I realize there are lots of tools for scripting, some of which may be superior to PowerShell; however, this blog will focus on that technology unless I can't figure out how to accomplish a task in PowerShell.

I'm also a firm believer in sharing code and other resources, so this blog is an attempt to share what I've figured out with others. Feel free to use anything you find here that is useful for your own work. All I ask is that if you find an error or bug, please let me know so I can fix my code.