Powershell Snippets

First/End of Month Date calculations

 
$dNow = get-date 
$dNowMonth = $dNow.Month 
$dNowYear = $dNow.Year 
#Use for beginning of month datetime search, first day at 00 am 
$firstDayOfMonth = get-date "$dNowMonth/1/$dNowYear" 
#Use for end of month datetime search, first day of next month at 00 am 
$lastDayOfMonth = $firstDayOfMonth.AddMonths(1) 
#Use this end of month search when you do not need the time value 
$ReallastDayOfMonth = $lastDayOfMonth.AddDays(-1) 
write-host "FirstDay = $firstDayOfMonth LastDay = $lastDayOfMonth RealLastDayOfMonth = $ReallastDayOfMonth" 

Create alias if does not exist

 
if ( -not (get-alias zip -ErrorAction SilentlyContinue)) 
    {new-item -path alias:zip -value "C:\Program Files\7-Zip\7z.exe"} 

Map the network drive if it does not exist( with “filesystem” fix for Test-Path on a network drive).

 
$drive = "H:" 
$remotedir = "\\myserver\SYSBACKUPS" 
$localdir = "F:\SYSBACKUPS\" 
$filesel = "sql_db_" + (get-Date -uformat "%Y%m%d") + ".7z" 
if (-not(Test-Path ($localdir+$filesel))) 
    {
    #We do not have the backup file so lets see if network drive is mapped 
    if (-not (Test-Path -path "filesystem::H:\")) 
        { 
        $net = new-object -ComObject WScript.Network
        $net.MapNetworkDrive($drive, $remotedir, $false, "username", "password")
        }
#... Insert rest of the code here
}

Parsing log files with Powershell

I found myself wanting to parsing a log file to find out which domain was getting the most newsletters. There are a variety of ways you can do this. Typically I would use Excel but there were more than 65K lines to import so I had to use something different. For kicks I did it in Powershell and here is how I did it in three lines. The log file is a tab delimited file without a header line. The field we are going to count is called, “RecipientDomain”.

 $header = "ServerFQDN","ServerDomain","IPAddress","MailTime","ClientDomain","RecipientDomain","Sender","Recipient","MessageID","Status","User","Size","ClientFQDN" 
$a = import-csv smtp-201007060000.csv -delimiter `t -header $header | where-object {($_.Status -eq "RECV=OK") } 
$a | group-object -property RecipientDomain -noelement | sort -property @{Expression="Count";Descending=$true}, @{Expression="Name";Descending=$false} | Select-object -First 20