Powershell: Syslog Module

From Rabbi Blog

Jump to: navigation, search

Purpose

Scratching a syslog itch with this one. It heavily uses the entry here and then builds in some specific things that I'm looking for.

  • Default severity and facility if not given
  • This one is for script driven items where outcomes should go out to syslog (audit trail) and will include $User and $Hostname
  • Intended for re-use among many scripts.

Note: Example has copious write-hosts, remove as needed.

Code

#We'd want to pass syslog($Message,$Severity,$Facility) for processing
# Reference: https://thwack.solarwinds.com/docs/DOC-194243
function syslog ($Message,$Severity,$Facility){
    Write-Host $Message "-" $Severity "-" $Facility
    If (!$Facility) {$Facility=22}
    #(16-23)=LOCAL0-LOCAL7
    If (!$Severity) {$Severity=6}
    #0=EMERG 1=Alert 2=CRIT 3=ERR 4=WARNING 5=NOTICE  6=INFO  7=DEBUG

    $Server = 'syslog'
    $User=$env:USERNAME
    
    $Hostname= $env:COMPUTERNAME
    # Create a UDP Client Object
    $UDPCLient = New-Object System.Net.Sockets.UdpClient
    $UDPCLient.Connect($Server, 514)
    # Calculate the priority
    $Priority = ([int]$Facility * 8) + [int]$Severity
    #Time format the SW syslog understands
    $Timestamp = Get-Date -Format "MMM dd HH:mm:ss"
    # Assemble the full syslog formatted message
    $FullSyslogMessage = "<{0}>{1} {2} {3} {4}" -f $Priority, $Timestamp, $Hostname, $User, $Message
    # create an ASCII Encoding object
    $Encoding = [System.Text.Encoding]::ASCII
    # Convert into byte array representation
    $ByteSyslogMessage = $Encoding.GetBytes($FullSyslogMessage)

    Write-Host $Message "-" $severity "-" $Facility


# Send the Message
#####-----####
$UDPCLient.Send($ByteSyslogMessage, $ByteSyslogMessage.Length)
#write-host $FullSyslogMessage
}

Usage

  • save as syslog.psm1 (or whatever name)
  • Import into ps1 script via
Import-Module .\syslog.psm1
  • Invoke by calling the function
syslog "dfasdf asdfadsfa" 3 1
syslog "dfasdf asdfadsfa" 6
syslog "dfasdf asdfadsfa" 4 7
syslog "dfasdf asdfadsfa"

Results

With the write-hosts enable, you should see that it returns the "quoted entry" and also the facility and severity. If no facility or severity were given, it will default to values in the module.

dfasdf asdfadsfa - 3 - 1
dfasdf asdfadsfa - 3 - 1
dfasdf asdfadsfa - 6 -
dfasdf asdfadsfa - 6 - 22
dfasdf asdfadsfa - 4 - 7
dfasdf asdfadsfa - 4 - 7
dfasdf asdfadsfa -  -
dfasdf asdfadsfa - 6 - 22