GPRS Online Log


posted by Archdeacon
01-04-2010

Downloads: 352
File size: 15kB
Views: 1,559

Embed
GPRS Online Log
  1. <# 
  2. .SYNOPSIS 
  3. Get-GprsTime (V4.0 Update for Windows 7 and allow time correction) 
  4.              (V4.4 'Interval' now incorporate previous 'FormatSpan' function
  5.              (V4.6 'Adjust' pattern will now reject times like '1:300:50'
  6. Check the total connect time of any GPRS SIM devices from a specified date.  
  7. Use 'Get-Help .\Get-GprsTime -full' to view Help for this script. 
  8. .DESCRIPTION 
  9. Display all the GPRS modem Event Log entries. While applications issued by the  
  10. mobile phone manufacturers will invariably monitor only their own usage, this 
  11. will show any logged GPRS activity, be it via PCMCIA, USB, mobile phone, etc. 
  12. Use the -Verbose switch for some extra information if desired. A default value 
  13. can be set with the -Monthly switch but can be temporarily overridden with any  
  14. -Start value and deleted by entering an invalid date.  Now uses .NET Parse to  
  15. use any culture date input. Switches -M and -S cannot be used together. 
  16.    A Balloon prompt will be issued in the Notification area for the 5 days  
  17. before the nominal month end.  
  18. NOTE:  this can effectively be suppressed by using a value higher than the SIM 
  19. card term, ie something like -Account 90 for a 30 day card which will override  
  20. the default setting.  
  21. Define a function in  $profile to set any permanent switches, for example to 
  22. remove 1hour 15 minutes from the total each time. 
  23. function GPRS { 
  24.    Invoke-Expression ".\Get-GprsTime -Adjust 1:15:00- $args"  
  25.  
  26. .EXAMPLE 
  27. .\Get-GprsTime.ps1 -Monthly 4/8/2011 
  28.  
  29. This will set the default search date to start from 4/8/2011 and is used to 
  30. reset the start date each month for the average 30/31 day SIM card. 
  31. .EXAMPLE 
  32. .\Get-GprsTime.ps1 -Start 12/07/2009 -Account 100 -Verbose 
  33.  
  34. Search from 12/07/2011 and also show (Verbose) details for each session. The 
  35. Account switch will override any balloon prompt near the SIM expiry date. 
  36. .EXAMPLE 
  37. .\Get-GprsTime.ps1 5/9/2011 -v 
  38.  
  39. Search one day only and show session details. 
  40. .EXAMPLE 
  41. .\Get-GprsTime.ps1 -Today 
  42.  
  43. Show all sessions for today. This always defaults to verbose output. 
  44. .EXAMPLE 
  45. .\Get-GprsTime.ps1 -Debug 
  46.  
  47. This shows the first available Event Log record & confirms switch settings.  
  48. (Note that it will probably not be the first 'RemoteAccess' or 'RasClient' 
  49. record). 
  50. .EXAMPLE 
  51. .\Get-GprsTime -Adjust 1:20:00 
  52. .\Get-GprsTime -Hours  1:20:00 
  53.  
  54. If the same SIM card is used on another computer then such times will have 
  55. to be added here manually (this should be put in a function in $profile so 
  56. that it will automatically be included - see example above). 
  57. To remove an amount of time, just put a '-' sign after the desired figure. 
  58. The alias 'Hours' may be used to distinguish from the 'Account' parameter. 
  59. .NOTES 
  60. A shorter total time than that actually used will result if the Event Log 
  61. does not contain earlier dates; just increase the log size in such a case. 
  62. The author can be contacted at www.SeaStarDevelopment.Bravehost.com and a 
  63. (binary compiled) Module version of this procedure is included in the file 
  64. Gprs3xxx.zip download there; the execution time of the module being about  
  65. 10 times faster than this script.  
  66. Use '(measure-Command {.\Get-GprsTime}).TotalSeconds' to confirm the times. 
  67. For the Event Log to record connect & disconnect events, the modem software 
  68. should be set to RAS rather than NDIS if possible. 
  69. #> 
  70.  
  71.  
  72. Param ([String] $start
  73.        [alias("HOURS")][string] $adjust
  74.        [String] $monthly
  75.        [Int]    $account = 0,      
  76.        [Switch] $today
  77.        [Switch] $verbose
  78.        [Switch] $debug
  79.  
  80. Trap [System.Management.Automation.MethodInvocationException] { 
  81.     [Int]$line = $error[0].InvocationInfo.ScriptLineNumber 
  82.     [System.Media.SystemSounds]::Hand.Play() 
  83.     if ($line -eq  213) { 
  84.         Write-Warning "[$name] Current GPRS variable has been deleted." 
  85.         $monthly = "" 
  86.         [Environment]::SetEnvironmentVariable("GPRS",$monthly,"User"
  87.     
  88.     else
  89.         Write-Warning "[$name] Date is missing or invalid $SCRIPT:form" 
  90.     
  91.     exit 1 
  92. #Establish the Operating System...We only need to confirm XP here. 
  93. #The result will be written to the 'out' variable '$osv'. 
  94. function Get-OSVersion($computer,[ref]$osv) { 
  95.    $os = Get-WmiObject -class Win32_OperatingSystem -computerName $computer 
  96.    Switch -regex ($os.Version) { 
  97.      '^5\.1\.(\d{1,4})$' { $osv.value = "xp" }          #Find XP & variants. 
  98.      default             { $osv.value = "unknown"
  99.    
  100. }  
  101.  
  102. $osv = $null 
  103. Get-OSVersion -computer 'localhost' -osv ([ref]$osv
  104. if ($osv -eq 'xp') { 
  105.     $logname = 'System' 
  106.     $connEvent = 20158 
  107.     $discEvent = 20159 
  108.     $source = 'RemoteAccess' 
  109. else {                                          #Treat As Vista or Windows 7. 
  110.     $logname = 'Application' 
  111.     $connEvent = 20225 
  112.     $discEvent = 20226 
  113.     $source = 'RasClient' 
  114. $entryType = 'Information' 
  115. $logEntry = $null 
  116. $source = 'Undetermined' 
  117. $oldest = Get-eventlog -LogName $logname |     #Get the earliest Log record. 
  118.              Sort-Object TimeGenerated | 
  119.                 Select-Object -first
  120. if ($oldest.TimeGenerated) {  
  121.     $logEntry = "$logname Event records available from - $($oldest.TimeGenerated.ToLongDateString())" 
  122. $name = $myInvocation.MyCommand 
  123. $newLine = "[$name] The switches -Start and -Monthly can only be used separately." 
  124. if ($debug) { 
  125.     $DebugPreference = 'Continue' 
  126. if ($start -and $monthly) { 
  127.     [System.Media.SystemSounds]::Hand.Play() 
  128.     Write-Warning "$newLine" 
  129.     exit 1 
  130. $SCRIPT:form = $null 
  131.  
  132. #In certain cases Culture & UICulture can be different and have been known to 
  133. # return conflicting results regarding '-is [DateTime]' queries, etc. 
  134. if ($Host.CurrentCulture -eq $Host.CurrentUICulture) { 
  135.     $SCRIPT:form = '-Use format mm/dd/year'                
  136.     [Int]$culture = "{0:%d}" -f [DateTime] "6/5/2009"        #Returns local day. 
  137.     if ($culture -eq 6) { 
  138.         $SCRIPT:form = '-Use format dd/mm/year' 
  139.     
  140. if ($SCRIPT:form) { 
  141.    $debugForm = $SCRIPT:form.Replace('Use format',''
  142.    Write-Debug "Current local system Date format is $debugForm" 
  143. $ErrorActionPreference = 'SilentlyContinue' 
  144. $VerbosePreference = 'SilentlyContinue' 
  145. $conn = $disc = $default = $print = $null               
  146. $timeNow = [DateTime]::Now  
  147. $total = $timeNow - $timeNow                     #Set initial value to 00:00:00. 
  148. $insert = "since" 
  149. if ($verbose) { 
  150.     $VerbosePreference = 'Continue' 
  151.  
  152. function CreditMsg ($value, $value2) { 
  153.     $value = [Math]::Abs($value
  154.     $prefix = "CURRENT" 
  155.     [DateTime] $creditDT = $value2  
  156.     $creditDT = $creditDT.AddDays($value)            #Add the -Account days. 
  157.     $thisDay = "{0:M/d/yyyy}" -f [DateTime]::Now           #Force US format. 
  158.     #If we use '$number = $creditDT - (Get-Date)' instead of the line below we 
  159.     #can sometimes get a value of 1 returned instead 2, hence the  above  lines. 
  160.     $number = $creditDT - [DateTime] $thisDay 
  161.     [String] $credit = $creditDT    
  162.     $credit = $credit.Replace('00:00:00','')      #Remove any trailing time. 
  163.     $credit = "{0:d}" -f [DateTime]$credit 
  164.     Switch($number.Days) { 
  165.         1            {$prefix = "($value days) will expire tomorrow"; break
  166.         0            {$prefix = "($value days) will expire today"; break
  167.         -1           {$prefix = "($value days) expired yesterday"; break
  168.         {($_ -lt 0)} {$prefix = "($value days) expired on $credit"; break
  169.         {($_ -le 5)} {$prefix = "($value days) will expire on $credit"
  170.         default      {$prefix = "CURRENT"}   #Only come here if over 5 days. 
  171.     
  172.     return $prefix 
  173.  
  174. function Interval ([String] $value) {     #Convert returns of '1.11:00:00'. 
  175.     Switch -regex ($value) { 
  176.         '^00?:00?:\d+(.*)$'    {$suffix = "seconds"; break
  177.         '^00?:\d+:\d+(.*)$'    {$suffix = "minutes"; break
  178.         '^\d+:\d+:\d+(.*)$'    {$suffix = "  hours"; break
  179.         '^(\d+)\.(\d+)(\D.*)$' {$suffix = "  hours" 
  180.                                  $pDays  = $matches[1] 
  181.                                  $pHours = $matches[2] 
  182.                                  [string]$pRest  = $matches[3] 
  183.                                  [string]$tHours = (([int]$pDays) * 24)+[int]$pHours 
  184.                                  $value  = $tHours + $pRest; break
  185.         default                {$suffix = "  hours"}  #Should never come here! 
  186.     
  187.     return "$value $suffix" 
  188.  
  189. function CheckSetting ($value) { 
  190.     if ($value) {                                #Correct for local culture. 
  191.        $print = $default.ToShortDateString()  
  192.     
  193.     else
  194.        $print = "(Value not set)" 
  195.     
  196.     return $print 
  197. #The Script effectively starts here............................................. 
  198. $getGprs = [Environment]::GetEnvironmentVariable("GPRS","User"
  199. #First check for GPRS variable and change from US date format to current locale. 
  200. if ([DateTime]::TryParse($getGprs, [Ref]$timeNow)) { #No error as date is valid. 
  201.     $default = "{0:d}" -f [datetime]$getGprs  
  202.     $default = [DateTime]::Parse($default)   
  203.     $checkParts = "{0:yyyy},{0:%M}" -f $default 
  204.     $times = $checkParts.Split(','
  205.     $dayCount = [DateTime]::DaysInMonth($times[0],$times[1])       #Range 28-31. 
  206.     if($account -eq 0) { 
  207.        $account = $dayCount 
  208.        $summary = "$($dayCount.ToString()) days"  
  209.     
  210.     else
  211.        $summary = "$($account.Tostring()) days" 
  212.     
  213.     $text = CreditMsg $account $getGprs  #Check if within 5 days of expiry date. 
  214.     if ($text -ne "CURRENT") { 
  215.        [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms"
  216.         $objNotifyIcon = New-Object System.Windows.Forms.NotifyIcon  
  217.         $objNotifyIcon.Icon = [System.Drawing.SystemIcons]::Exclamation  
  218.         $objNotifyIcon.BalloonTipIcon  = "Info"  
  219.         $objNotifyIcon.BalloonTipTitle = "GPRS online account" 
  220.         $objNotifyIcon.BalloonTipText  = "Credit $text" 
  221.         $objNotifyIcon.Visible = $True  
  222.         $objNotifyIcon.ShowBalloonTip(10000) 
  223.     
  224. else
  225.     $summary = "(Days not set)" 
  226.     if ((!$today) -and (!$monthly) -and (!$start)) { 
  227.        [System.Media.SystemSounds]::Hand.Play() 
  228.        Write-Warning("Monthly date is either invalid or not set."
  229.        exit 1 
  230.     
  231. if ($start) { 
  232.     $start = [DateTime]::Parse($start)                 #Trigger TRAP if invalid! 
  233.     [DateTime]$limit = $start 
  234.     $convert = "{0:D}" -f $limit 
  235.     $print = CheckSetting $default 
  236. }  
  237.  
  238. if ($monthly) { 
  239.     $start = [DateTime]::Parse($monthly)               #Trigger TRAP if invalid! 
  240.     Write-Output "Setting GPRS (monthly) environment variable to: $monthly" 
  241.     $gprs = [String]$start.Replace('00:00:00',''
  242.     [Environment]::SetEnvironmentVariable("GPRS",$gprs,"User"
  243.     [DateTime] $limit = $start               #Change to required US date format. 
  244.     $convert = "{0:D}" -f $limit 
  245.     $print = $limit.ToShortDateString() 
  246.     $summary = "(Days undetermined)"            #Will show next time around. 
  247.  
  248. if ($today) {                     
  249.     $verBosePreference = 'Continue'                    #Show VERBOSE by default. 
  250.     [DateTime] $limit = (Get-Date
  251.     $convert = "{0:D}" -f $limit 
  252.     $limit = $limit.Date         #Override any start date if using -Today input. 
  253.     $insert = "for today" 
  254.     $print = CheckSetting $default 
  255. if ((!$today) -and (!$monthly) -and (!$start)) {         
  256.     if ($default) { 
  257.        $monthly = $default 
  258.        [DateTime] $limit = $monthly 
  259.        $convert = "{0:D}" -f $limit 
  260.        $print = CheckSetting $default 
  261.     
  262.  
  263. $adjustment = $null  #Otherwise 'Set-Strictmode -Version latest' will catch. 
  264. if ($adjust) { 
  265.    $pattern = '^(\d{1,3}):([0-5]?[0-9]):([0-5]?[0-9])-?$' 
  266.    if ($adjust -notmatch $pattern ) {  
  267.       Write-Warning "Invalid input ($adjust) - use <hours>:<minutes>:<seconds>" -WarningAction Continue 
  268.       return 
  269.    }  #Now create the 'adjustment' to add later. 
  270.    $adjustment = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3] 
  271.    $outString =  $adjust.Replace('-',''
  272.    $outString = interval $outString 
  273.  
  274. Write-Verbose "All records $($insert.Replace('for ','')) - $convert" 
  275. Write-Verbose "Script activation - User [$($env:UserName)] Computer [$($env:ComputerName)]" 
  276. Write-Output "" 
  277. Write-Output "Calculating total connect time of all GPRS modem devices..." 
  278.                 #We cannot proceed beyond here without a valid $limit value. 
  279. Write-Debug "Using - [Search date] $($limit.ToShortDateString()) [Account] $summary [GPRS Monthly] $print" 
  280. if ($logEntry) {                     
  281.     Write-Debug "$logEntry" 
  282.  
  283. $lines = Get-EventLog $logname | Where-Object {($_.TimeGenerated -ge $limit) -and
  284.     ($_.EventID -eq $discEvent -or $_.EventID -eq $connEvent)}   
  285. if ($lines) { 
  286.     Write-Verbose "A total of $([Math]::Truncate($lines.Count/2)) online sessions extracted from the $logname Event Log." 
  287. else
  288.     Write-Output "(There are no events indicated in the $logname Event Log)" 
  289.     exit 2                                       #No need to go any further. 
  290. $lines | ForEach-Object
  291.     try { 
  292.        $source = $_.Source 
  293.     
  294.     catch { 
  295.        return 
  296.     
  297.     if ($_.EventID -eq $discEvent) {                    #Event 20159 is Disconnect. 
  298.        $disc = $_.TimeGenerated 
  299.     }  
  300.     else {                                              #Event 20158 is Connect. 
  301.        $conn = $_.TimeGenerated     
  302.     }                  #We are only interested in matching pairs of DISC/CONN... 
  303.     if ($disc -ne $null -and $conn -ne $null -and $disc -gt $conn) { 
  304.        $diff = $disc - $conn 
  305.        $total += $diff 
  306.        $convDisc = "{0:G}" -f $disc 
  307.        $convConn = "{0:G}" -f $conn 
  308.        $period = interval $diff 
  309.        Write-Verbose "Disconnect at $convDisc. Online - $period" 
  310.        Write-Verbose "   Connect at $convConn." 
  311.     
  312. }   #End ForEach 
  313. Write-Verbose "Using local event source - $logname Event Log [$source]" 
  314. $period = interval $total 
  315.  
  316. if ($adjustment -and ($total -match $pattern)) { 
  317.    $outDate = New-TimeSpan -hours $matches[1] -minutes $matches[2] -seconds $matches[3] 
  318.    if (!$adjust.EndsWith('-')) { 
  319.       $period = $outDate + $adjustment    #The '-adjust' value added at start. 
  320.       $temp = [String]$period   #Extract any 1.0:00:00 values if + 24 hours. 
  321.       Write-Debug "Processing (Timespan) string: $temp" 
  322.       $show = (interval $temp).Replace('   ',' '
  323.       Write-Output "Total online usage $insert $convert is $show" 
  324.       Write-Output "(including $($outString.Replace('   ',' ')) adjustment time)" 
  325.    
  326.    else
  327.       if ($outDate.TotalSeconds -gt $adjustment.TotalSeconds) { 
  328.          $period = $outDate - $adjustment 
  329.          $temp = [String]$period 
  330.          Write-Debug "Processing (Timespan) string: $temp" 
  331.          $show = (interval $temp).Replace('   ',' '
  332.          Write-Output "Total online usage $insert $convert is $show" 
  333.          Write-Output "(excluding $($outString.Replace('   ',' ')) adjustment time)" 
  334.       
  335.       else
  336.          $adjust = $adjust.Replace('-',''
  337.          Write-Output "Total online usage $insert $convert is $($period.ToString().Replace('   ',' '))." 
  338.          Write-Warning "Total usage exceeded ($adjust) - no adjustment performed" 
  339.       
  340.    
  341. else
  342.    Write-OutPut "Total online usage $insert $convert is $($period.ToString().Replace('   ',' '))." 
  343. Write-Output "" 
Filed under: , , , ,

Scan the System Event log for all GPRS online activity - PCMCIA, USB, mobile phone, etc. A Balloon Tip will also be issued when the SIM card is within 5 days of expiry. (Note that the size of the Event Log should be set at the maximum possible length in order to retain as many relevant events as possible).

Concentrated Tech NSoftware Dell Compellent Sponsored by Idera and Concentrated Tech and NSoftware and Dell Compellent
Copyright 2011 PowerShell.com. All rights reserved.