Json Over TCP With Powershell


Logging is a critical part of any application written in any language. If you want to catch the anomalies in your scripts, you will need to find a way to write logs efficiently and find a way to query these logs and do some analytics on them. Over the years, I’ve been using a set of functions which make the ‘logging part’ of scripting a lot easier and more consistent.

Over the years, I’ve been scripting in Powershell, Bash, Python, Perl and PHP. The first thing I start with when creating a new script is paste my logging function of the language I’m working in.

As most of my scripts are written in Powershell, I’ll start with blogging about my Write-Log Powershell function. This function allows you to write logs to a variety of different targets. Maybe I’ll post some details about my log functions for other languages later.

Powershell – Write-Log

We were unable to make it work with the Json charset CP1252, as Logstash considered each line in the json file as a separate log entry. Only after stripping each newline, carriage return and space from the json object were we able to get Logstash to recognize it.  Anyway it seems more logical to not make your script log to file anymore when you can use an elk stack or a Nagios Log Server.

Being able to send Json over TCP with this Powershell function kind of makes it a lot easier to test and stress your configurations. It also kind of obsoletes logging to file and querying and filtering your logs with Elasticsearch is much more fun then reading through your logs with notepad…

How to achieve Json Over TCP with Powershell?

The function enables you to send json over tcp to a specific input port on your Nagios Log Server. A small example how you get the above to work:

Together with this input:

Should result in something like this:


This again opens up a lot of new possibilities. I’ll try to expand this post with some use cases.