Windows Server 2016 Automation with PowerShell Cookbook(Second Edition)
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Run webtutil to turn on printer monitoring:
      $log = 'Microsoft-Windows-PrintService'
webtutil.exe sl $log /operational /Enabled:true
  1. Define a Function:
    1. Specify the Function header for an advanced function:
           Function Get-PrinterUsage {
           [CmdletBinding()]
           Param()
  
    1. Get the events from the PrintService event log:
            $Dps = Get-WinEvent -LogName 
Microsoft-Windows-PrintService/Operational |
Where-Object ID -eq 307
    1. Create a hash table for each event log record:
                 Foreach ($Dp in $Dps) {
                     $Document = [Ordered] @{}
    1. Populate the hash table with properties from the event log entry:
              $Document.Id       = $dp.Properties[0].value
              $Document.Type     = $dp.Properties[1].value
              $Document.User     = $dp.Properties[2].value
              $Document.Computer = $dp.Properties[3].value
              $Document.Printer  = $dp.Properties[4].value
              $Document.Port     = $dp.Properties[5].value
              $Document.Bytes    = $dp.Properties[6].value
              $Document.Pages    = $dp.Properties[7].value
    1. Create an object for this printer usage entry:
              $UEntry = New-Object -Type PSObject 
-Property $Document
    1. Give it a better type name:
            $UEntry.PsTypeNames.Clear()
            $UEntry.PsTypeNames.Add("Packt.PrintUsage")
    1. Output the entry:
            $UEntry
            } # End of foreach
            } # End of function
  1. Set and use an alias to get the printer usage:
            Set-Alias -Name GPRU 
-Value Get-PrinterUsage
GPRU | Format-Table