Documentation forKiwi Syslog Server

Examples of PowerShell scripts used in KSS NG

When you add an action to run a script in Kiwi Syslog Server NG, use the following examples to help you write the script.

The current version of KSS NG only supports PowerShell scripts.

Use variables in a script

See Script variables used in KSS NG for detailed information about variables.

# File path and name
$path = "C:\logs\"
$fileName = "testVars.txt"
$fullPath = Join-Path $path $fileName

# Original values
$originalCommonValues = "__VarFacility: $($Common.VarFacility) __VarLevel: $($Common.VarLevel) __VarInputSource: $($Common.VarInputSource) __VarPeerAddress: $($Common.VarPeerAddress) __VarPeerName: $($Common.VarPeerName) __VarPeerDomain: $($Common.VarPeerDomain) __VarCleanMessageText: $($Common.VarCleanMessageText)"
$originalOtherValues = "__VarDate: $($Other.VarDate) __VarTime: $($Other.VarTime) __VarMilliSeconds: $($Other.VarMilliSeconds) __VarSocketPeerAddress: $($Other.VarSocketPeerAddress) __VarPeerAddressHex: $($Other.VarPeerAddressHex) __VarPeerPort: $($Other.VarPeerPort) __VarLocalAddress: $($Other.VarLocalAddress) __VarLocalPort: $($Other.VarLocalPort) __VarPriority: $($Other.VarPriority) __VarRawMessageText: $($Other.VarRawMessageText)"
$originalGlobalValues = "__VarGlobal01: $($Global['VarGlobal01']) __Global[age]: $($Global['age'])"
$originalCustomValues = "__Custom[customName1]: $($Custom['customName1']) __Custom[varName1]: $($Custom['varName1'])"

# Common variables
$Common.VarFacility++
$Common.VarLevel++
$Common.VarInputSource++
$Common.VarPeerAddress++
$Common.VarPeerName++
$Common.VarPeerDomain++
$Common.VarCleanMessageText++

# Other variables
$Other.VarDate++
$Other.VarTime++
$Other.VarMilliSeconds++
$Other.VarSocketPeerAddress++
$Other.VarPeerAddressHex++
$Other.VarPeerPort++
$Other.VarLocalAddress++
$Other.VarLocalPort++
$Other.VarPriority++
$Other.VarRawMessageText++

# Custom \ Global variables (you can set any names for Global and custom variables)
if (-not $Global.ContainsKey("age")) {
    $Global["age"] = 5
    $Global["VarGlobal01"] = 1
    $Custom["customName1"] = "KSS NG"
    $Custom["varName1"] = 0
} else {
    $Global["age"]++
    $Global["VarGlobal01"]++
    $Custom["customName1"]++
    $Custom["varName1"]++
}

# Changed values
$changedCommonValues = "__VarFacility: $($Common.VarFacility) __VarLevel: $($Common.VarLevel) __VarInputSource: $($Common.VarInputSource) __VarPeerAddress: $($Common.VarPeerAddress) __VarPeerName: $($Common.VarPeerName) __VarPeerDomain: $($Common.VarPeerDomain) __VarCleanMessageText: $($Common.VarCleanMessageText)"
$changedOtherValues = "__VarDate: $($Other.VarDate) __VarTime: $($Other.VarTime) __VarMilliSeconds: $($Other.VarMilliSeconds) __VarSocketPeerAddress: $($Other.VarSocketPeerAddress) __VarPeerAddressHex: $($Other.VarPeerAddressHex) __VarPeerPort: $($Other.VarPeerPort) __VarLocalAddress: $($Other.VarLocalAddress) __VarLocalPort: $($Other.VarLocalPort) __VarPriority: $($Other.VarPriority) __VarRawMessageText: $($Other.VarRawMessageText)"
$changedGlobalValues = "__VarGlobal01: $($Global['VarGlobal01']) __Global[age]: $($Global['age'])"
$changedCustomValues = "__Custom[customName1]: $($Custom['customName1']) __Custom[varName1]: $($Custom['varName1'])"

# Delimiter for script execution
$scriptStart = "================== Script Execution Start =================="
$scriptEnd = "================== Script Execution End =================="

# Output to file
$separator = "==============="
$scriptStart | Add-Content -Path $fullPath
Add-Content -Path $fullPath -Value "$separator Common Values: $separator"
$originalCommonValues, $changedCommonValues | Add-Content -Path $fullPath
Add-Content -Path $fullPath -Value "$separator Other Values: $separator"
$originalOtherValues, $changedOtherValues | Add-Content -Path $fullPath
Add-Content -Path $fullPath -Value "$separator Global Vars: $separator"
$originalGlobalValues, $changedGlobalValues | Add-Content -Path $fullPath
Add-Content -Path $fullPath -Value "$separator Custom Vars: $separator"
$originalCustomValues, $changedCustomValues | Add-Content -Path $fullPath
$scriptEnd | Add-Content -Path $fullPath


# Output to console
Write-Host $scriptStart
Write-Host "$separator Common Values: $separator"
Write-Host $originalCommonValues
Write-Host $changedCommonValues
Write-Host "$separator Other Values: $separator"
Write-Host $originalOtherValues
Write-Host $changedOtherValues
Write-Host "$separator Global Vars: $separator"
Write-Host $originalGlobalValues
Write-Host $changedGlobalValues
Write-Host "$separator Custom Vars: $separator"
Write-Host $originalCustomValues
Write-Host $changedCustomValues
Write-Host $scriptEnd

Log a message to a specified file

# Note: This script requires Read access to "Other fields" variables.
# Ensure that the Fields read/write permissions are set as below.

#                Read | Write
# Common fields    X  |
# Other fields     X  |
# Custom fields       |  X

# File path and name
$path = "C:\logs\"
$fileName = "testScript_logToFile.txt"
$fullPath = Join-Path $path $fileName

# Ensure the directory exists, create it if not
$Directory = Split-Path -Path $fullPath
if (-not (Test-Path -Path $Directory -PathType Container)) {
    New-Item -ItemType Directory -Path $Directory -Force
}

# Message details
$MsgPriority = "Local7.Info"
$MsgHostAddress = $Common.VarPeerName
$MsgDate = "$($Other.VarDate) $($Other.VarTime)"
$MsgText = "This is a test message from the scripting action"

# Construct the data string
$Data = "$MsgDate `t $MsgPriority `t $MsgHostAddress `t $MsgText"


# Log the message to the specified file
Add-Content -Path $fullPath -Value $Data -Force

Check the number of broken links in a message

function Main {
    # The fields are available via  $Common and $Global objects

    if ($Common.VarCleanMessageText.ToLower().Contains("link down")) {
        if (-not $Global["Stats01"]) {
            $Global["Stats01"] = 0
        }

        $Global["Stats01"]++
    }

    # Set the return value to indicate that the script ran correctly
    $Main = "OK"
}

# Call the Main function
Main

Check if messages contain specified text

function Main {
    # The fields are available via the $Common and $Global objects

    # Text to check
    $textToCheck = "Test1"

    if ($Common.VarCleanMessageText -match $textToCheck) {
        $Global["result_ContainsText"] = "Message contains '$textToCheck'. "
    } else {
        $Global["result_ContainsText"] = "Message does not contain '$textToCheck'."
    }

    # Set the return value to indicate that the script ran correctly
    $Main = "OK"
}

# Call the Main function
Main

Replace text in a message with specified text

# Replace cat with dog within the message text field
# Case insensitive replace 
$Common.VarCleanMessageText = $Common.VarCleanMessageText -replace "cat", "dog"

# OR
# Case sensitive replace 
$Common.VarCleanMessageText = $Common.VarCleanMessageText.Replace('Message','LOG(replaced)')

# Return OK to indicate that the script ran correctly.
$Main = "OK"

Send an email message

# Set the return value to indicate that the script ran correctly.
$Main = "OK"

# Email configuration
$MailTo = "joe@company.com"
$MailFrom = "server@company.com"
$MailSubject = "Syslog message received"
$MailMessage = $Common.VarCleanMessageText

$MailPriority = "Normal"    # Specify "Normal" for Normal Priority

# SMTP server configuration without SSL
$SMTPServer = "127.0.0.1"
$SMTPPort = 25  # Use the appropriate port for non-secure connections


# Use Try-Catch for error handling
try {
    Send-MailMessage -To $MailTo -From $MailFrom -Subject $MailSubject -Body $MailMessage -Priority $MailPriority -SmtpServer $SMTPServer -Port $SMTPPort
    Write-Host "Email sent successfully."
} catch {
    Write-Host "Failed to send email. $_"
}

Send a syslog message

# Set the return value to indicate that the script ran correctly.
$Main = "OK"

# Define syslog parameters
$Server = "127.0.0.1"    # Remote syslog host
$Port = 514                # Use the standard syslog port
$Severity = '6'
$Facility = '22'
$Hostname= 'solarWindsTest'
$Message = "This is an example of a syslog message"

# Construct the syslog message
$Priority = ([int]$Facility * 8) + [int]$Severity
$Timestamp = Get-Date -Format "MMM dd HH:mm:ss"
$FullSyslogMessage = "<{0}>{1} {2} {3}" -f $Priority, $Timestamp, $Hostname, $Message
$Encoding = [System.Text.Encoding]::ASCII
$ByteSyslogMessage = $Encoding.GetBytes($FullSyslogMessage)

# Create a UDP client
$UdpClient = New-Object System.Net.Sockets.UdpClient
$UDPCLient.Connect($Server, $Port)

# Convert the message to bytes
$MessageBytes = [System.Text.Encoding]::ASCII.GetBytes($Message)

# Send the message
$UDPCLient.Send($ByteSyslogMessage, $ByteSyslogMessage.Length)


# Close the UDP client
$UdpClient.Close()

Split space-delimited message text into separate custom fields

# This script will split the space-delimited message text into separate custom fields

# Split the data into an array based on the " " (space) delimiter
$SplitData = $Common.VarCleanMessageText -split " "


# Find the number of fields and write it to custom variables
$Max = $SplitData.Count - 1
if ($Max -ge 0) { $Custom["VarCustom1"] = $SplitData[0] }
if ($Max -ge 1) { $Custom["VarCustom2"] = $SplitData[1] }
if ($Max -ge 2) { $Custom["VarCustom3"] = $SplitData[2] }
if ($Max -ge 3) { $Custom["VarCustom4"] = $SplitData[3] }
if ($Max -ge 4) { $Custom["VarCustom5"] = $SplitData[4] }
if ($Max -ge 5) { $Custom["VarCustom6"] = $SplitData[5] }
if ($Max -ge 6) { $Custom["VarCustom7"] = $SplitData[6] } 

# Or Set custom fields using a loop
for ($i = 0; $i -le $SplitData.Count - 1; $i++) {
    $CustomFieldName = "VarCustom" + ($i + 1).ToString("D2")
    $Custom["$CustomFieldName"] = $SplitData[$i]
}
<# Note: 

.ToString("D2"): Converts the numeric value to a string with at least two digits, padding with leading zeros if necessary. This ensures that the field names have a consistent format, particularly when $i + 1 is a single-digit number.
"VarCustom" + ...: Concatenates the string "VarCustom" with the formatted loop iteration number to create a custom field name.

So, for example, if $i is 0, the resulting $CustomFieldName would be "VarCustom01". If $i is 9, the resulting $CustomFieldName would be "VarCustom10". This way, the script generates custom field names with a two-digit suffix, maintaining a consistent and organized naming convention. #>

# Set the return value to indicate that the script ran correctly
$Main = "OK"

The scripts are not supported under any SolarWinds support program or service. The scripts are provided AS IS without warranty of any kind. SolarWinds further disclaims all warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The risk arising out of the use or performance of the scripts and documentation stays with you. In no event shall SolarWinds or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the scripts or documentation.