PowerShell is a powerful automation and configuration management framework that can be used to configure your Windows systems. With PowerShell, you have the power of scripting at your fingertips which allows for more flexibility than any other means. This article will show how you can use PowerShell as well as the PSFramework Module in order to quickly create tools and scripts that automate tasks on your machines without any hassle.
The “write-log” is a PowerShell command that can be used to log events. The PSFramework Module is an extension of PowerShell that allows you to use the PSFramework commands with PowerShell.
It’s critical, particularly in a production setting, to be able to monitor what PowerShell scripts are doing. Troubleshooting, auditing, and analyzing possible security vulnerabilities all need the recording of activities. You can take your logging to a whole new level using PowerShell and a community module called PSFramework, which you’ll learn about in this post!
This article is for you if you often use the Write-Host cmdlet to show error information or manually register Windows event sources.
If you want a simple, scalable PowerShell logging solution that can either write to a text file or integrate with a log management system, stick with us.
Creating More Effective Log Messages
Before you can decide on the best way to produce logs using PowerShell, you must first learn how to write better log messages.
There are a variety of reasons to keep logs. The famed error message is one of the most prevalent. Depending on how you look at things, error messages may be beneficial or destructive.
You’ve almost certainly seen some obnoxious error messages in your time. PC LOAD LETTER is a great illustration if you’ve ever watched the movie Office Space.
If your error messages make people wonder, “What does that mean?” you might consider revising them! Logs should be easy to read and understand.
Make Events Operational
By itself, a log report suggesting a cryptic PC LOAD LETTER error message makes little sense. No one, including you, will understand what that message means in a few years! For actionable error scenarios, you should always produce log messages.
What would you think if the PC LOAD LETTER notice instead stated, “PC LOAD LETTER: Check the specifications on the rotating girder?” If everything checks out, contact vendor support for further information”? You’d probably be able to hold your cool a little better and get a head start on solving the issue.
Keep logs simple and easy to read for humans.
The information in the logs must be legible by humans. Include enough details to make the occurrence actionable rather than relying on conjecture. You may be exact, but make sure that someone else understands what the event signifies, even if just on a basic level.
Logging may be as simple or as complex as you want it to be. Simple logs make troubleshooting easy for everyone involved.
Windows Logging Options
What comes to mind when you hear the term ‘log’ in IT? You’re probably thinking about log files right now. Although log files are a possibility, and one that will be discussed in this article, they are not the only one.
The Windows Event Log is another option. In Windows, the Windows Event Log and its apparently infinite number of log streams are widespread. You may write logs with varied degrees of severity, sources, categories, messages, and more in the event log.
Because it is structured, the Windows Event Log differs from a log file. A log file is a basic text file on its own. The developer is responsible for creating a schema for the log messages. The structure is already in place in the Windows Event log.
We’ll go through how to use PowerShell to interact with the event log in this tutorial. Using the PSFramework PowerShell module, we’ll also go through logging using log files.
Prerequisites
This article will be a walkthrough for the rest of it. If you’re going to follow along, make sure we’re both on the same page. You’ll need the following items to go through each section of this article:
The Windows Event Log is used to record events.
The Windows Event Log is one technique to collect logging information with PowerShell. As previously stated, the Windows Event Log already has a schema for you to work with. It also contains GUI tools for creating and parsing event log messages, such as the Windows Event Viewer and PowerShell cmdlets.
The Write-EventLogcmdlet is the principal PowerShell cmdlet for writing log events to the Windows Event Log. You may use the Write-EventLog cmdlet to create new log events in existing event logs. The Write-EventLog cmdlet is all you need if you’re going to use existing event sources like the Application, Security, and System event logs.
Sources are a notion in the Windows Event Log. In a nutshell, a source is a container for storing event log messages. Built-in sources, for example, are utilized to distinguish between operating system-specific and software-specific events.
If you want your log message to appear in a default source, you may use existing sources to publish events to. You may, however, construct your own sources to help distinguish your custom-generated event log messages from the others.
Creating a Source for Event Logs
The New-EventLog cmdlet may be used to establish a custom event log source. This cmdlet changes the registry to make your event log a Windows first-class citizen.
Create a new event log source with a name and dsource in an administrator PowerShell console, as illustrated below.
PS51> New-EventLog -LogName ‘Application’ -Source ‘ATA_Script’’
You’ll see an error like this if you don’t have the right permissions or are performing the command in a non-elevated PowerShell console session.
Using PowerShell to create a Windows event log source
Adding Entries to the Event Log
After you’ve defined a source for your script/application, you can get down to work by using the Write-EventLog cmdlet to generate event log messages.
An example of writing an event log message to the Application event log using the newly formed event source (ATA Script) is shown below. This communication is a one-of-a-kind Informational occurrence.
PS51> Write-EventLog -LogName ‘Application’ -Source ‘ATA_Script’ -EntryType ‘Information’ -EventID 1 -Message ‘Everything is broken. Everything is cool when you’re part of a team!’
After you’ve generated the event, you can look for it in the Windows Event Viewer or using PowerShell’s Get-WinEvent or Get-EventLog cmdlets. The Get-EventLog cmdlet is used in the example below to locate all Informational events using the event source that was recently established. If more than one event is provided, the most recent one is returned.
PS51> Get-EventLog -LogName ‘Application’ -EntryType ‘Information’ -Source ‘ATA_Script’’ -Newest 1
Using PowerShell to query an event log
Best Practices for Event Sources
It’s critical that you understand a gotcha before moving on from this section. In the sample above, PowerShell is utilizing the previously generated arbitrary registered source (ATA Script). To write an item to the Windows Application log, you’ll need this source.
This kind of custom source works nicely for basic cases such as:
- A bespoke Windows service’s event logging.
- The output of a basic PowerShell function is recorded.
- Providing a process with a trigger event.
As a best practice, as indicated in the first step, create a separate event source for each script that you wish to produce event log entries. It’s simpler to keep track of what’s causing the event log entries if you do it this way. Assume you have five scripts, each doing a single job. How could you tell which script failed if they were all utilizing the same event source? Adding a new event source to your logging sources helps you arrange them.
Taking Advantage of Transcript of PowerShells
Although the strategy you’re going to discover is effective, it isn’t the most efficient. In a moment, you’ll understand why.
The Write-Host cmdlet is excellent for providing visual feedback as a script starts, but it isn’t very good at logging. Why?
- A single PowerShell session generates the output. The output vanishes when the session is closed.
- The cmdlet’s modification options are limited to the text’s foreground and background colors.
You can see an example of the Write-Host cmdlet in action below.
To deliver output, use Write-Host.
Although this output is only presented in the PowerShell console by default and is not recorded anywhere else, Transcript of PowerShells may be used.
You may produce transcripts (text files) with the Start-Transcript cmdlet, which captures all output delivered to a PowerShell console. The Start-Transcript cmdlet is an excellent approach to keep track of what happens in a PowerShell session.
The Start-Transcript cmdlet begins recording console action to a new transcript, while the Stop-Transcript cmdlet terminates it. Here’s an example of what I’m talking about.
Using PowerShell to start and stop a transcript
While utilizing the Write-Host cmdlet with Transcript of PowerShells is theoretically possible, it isn’t the best method. In the sample below, take note of what the transcript includes. The log is tough to read, and parsing it is almost impossible!
Transcript of PowerShell
Using the PSFramework PowerShell Module to Log
It’s time to start logging to text files, as promised! There’s no need to create your own log file solution utilizing a mix of Add-Content, Set-Content, and other PowerShell cmdlets. PSFramework is a free PowerShell module that you may use!
PSFramework is a PowerShell module that lets you record activities in a number of situations.
Important Concepts in the PSFramework
Providers
Providers are a crucial notion in the PSFramework module. Providers are references to different locations where logs should be kept. A provider might be anything as simple as a file, such as Kiwi Log Server, Elasticsearch, loggly, or Graylog (usually text).
Although the PSFramework module is extendable, you receive three providers to utilize right away when you download it:
- Filesystem — With an automated seven-day retention and rotation, this service writes all Message Flows you produce to the currently logged-in user’s percent APPDATA% folder. The default provider is the filesystem.
- PSFramework may deliver log Message Flows to an open source log management named Graylog via the Gelf provider. When utilizing this option, there is a bit extra preparation required.
- Logfile — With this provider, you may define a file to which all messages will be written. The default output format is CSV since log files might be of many formats. This implies that typical log file extensions like.txt,.log, and.csv may be used. It’s all up to you.
Message Flows
Message Flows contain output from commands. These are used to classify information being recorded in the logs. Common streams are Verbose, Debug, Information, Error and Warning. You can read more about available streams using Help about_psf_message .
Let’s get down to business and explore what the PSFramework module can achieve!
PSFramework should be installed.
The first step is to get this module downloaded and installed. Install-Module -Name PSFramework -Scope CurrentUser -Scope CurrentUser -Scope CurrentUser -Scope CurrentUser -Scope CurrentUser -Scope CurrentUser -Scope CurrentUser -Scope Instead of being placed in the system path, the module will be placed in my user profile. Use the Scope argument if you want the module to be accessible to all users on your system.
Once installed, you’ll have access to all of the cmdlets needed to complete the code examples in the remainder of this tutorial.
Creating a Service Provider
With the default PSFramework setup, you may pick among three registered and installed providers: filesystem, logfile, and greylog. If you wish to utilize a different provider, you must first register with PSFramework and then install that provider. You must enable one of these providers before you can start writing to logs.
Set-PSFLoggingProvider is the command to enable a provider. The Name and Enable arguments are needed for this cmdlet. Each option will be used to enable the provider or providers you want to work with.
You’ll need to perform the Register-PSFLoggingProvider and Install-PSFLoggingProvider cmdlets if you want to use your own provider. This article’s scope does not include these cmdlets or scenario. Consult the built-in help given with the module if you want to learn more about this option. There are a few examples that may help you improve on your current skills and have a better knowledge of how logging works.
For this demonstration, you’ll be using the logfile provider. Since this provider is off by default, you must first enable the provider so that Message Flows can be sent to it. Using the Set-PSFLoggingProvider command, you can do that no sweat:
Set-PSFLoggingProvider -Name ‘logfile’ -Enable $true Set-PSFLoggingProvider -Name ‘logfile’ Set-PSFLoggingProvider -Name ‘
If you wish to remain with the filesystem provider, you don’t have to do anything since it’s already enabled.
Run the Get-PSFLoggingProvider command to view all of the presently registered providers. The output from this command should look like the screenshot below.
Providers of PSFramework logging
Now that you’ve enabled a provider, you can begin sending Message Flows to that provider you wish to use for your logging solution.
Using the filesystem Provider for logging
The filesystem provider makes it simple to start logging without having to set up log file storage locations. It’s ideal for short-term logging requirements, but not for long-term diagnostic logging.
In this filesystem provider example, you’ll learn how to utilize the Write-PSFMessage cmdlet. Consider the following scenario: you already have a PowerShell script that runs a service on a remote computer. The service may fail to start for a variety of reasons, and the resulting failures are not recorded. The following is an example.
Start-Service -Name ‘BITS’ Invoke-Command -ComputerName ‘Lab01.domain.local’ -ScriptBlock
You want to know whether the Start-Service command can start the service successfully and if it fails. You achieve this by making Start-Service produce a terminating error and then adding try/catch blocks to capture any problems that occur.
try { Start-Service -Name ‘BITS’ Invoke-Command -ComputerName ‘Lab01.domain.local’ -ScriptBlock -ErrorAction Stop } catch { }
You must now keep track of when Start-Service succeeds and when it fails. You’re aware that if Invoke-Command fails, PowerShell will execute the code included inside the catch block rather than any code executed after Invoke-Command.
Compare this to a success, in which the code following the Invoke-Command is executed. You determine that theWrite-PSFMessage command should be used in the right locations.
If the code runs correctly, Write-PSFMessage will record a useful message with the level of Important and the tag Success, as seen below.
try { Start-Service -Name ‘BITS’ Invoke-Command -ComputerName ‘Lab01.domain.local’ -ScriptBlock -ErrorAction Stop Write-PSFMessage -Level Important -Message ‘Successfully started BITS.’ -Tag ‘Success’ } catch { Write-PSFMessage -Level Warning -Message ‘Error starting BITS.’ -Tag ‘Failure’ -ErrorRecord $_ }
The Tags feature was used in the example above. Tags aren’t required, although they do make it simpler to categorize and search a log. Tags are a kind of free text that allows you to create your own. SUCCESS, FAILURE, ERROR, and INFO are some of the most popular tags.
If the command fails, a warning will be shown in the PowerShell console, as seen below.
PSFramework log provider for filesystems
Viewing the Log of the Filesystem
Once you’ve written a few Message Flows with the filesystem provider, you can use the Get-PSFMessage cmdlet to query the log.
If the code in the previous example produced log messages at the Warning level, you could view all of them by setting the Level parameter to Warning. You can see an example of how to achieve this, as well as the sort of output you’ll get.
PS51> Get-PSFMessage -Level Warning
Messages from the logs may be queried.
Using the logfile Provider for logging
Now that you’ve seen how the filesystem provider works, let’s check out the logfile provider. The logfile providers allows you to write Message Flows to plain-text files, by default, in a CSV format.
To utilize the logfile provider, instruct PSFramework not to use the default provider (filesystem) and to provide a file to which messages should be recorded. Use the Set-PSFLoggingProvider cmdlet to do so. You can see how to achieve this in the example below.
- using the Name argument, the name of the provider (logfile)
- Changing the value of the Enabled attribute to True
- changing the FilePath value to the target file
PS51> Set-PSFLoggingProvider -Name logfile -Enabled $true -FilePath ‘C:My_Events.log’
Note: Make sure the provider is specified at the start of your script!
PSFramework will record a message that is received by using the Write-PSFMessage command as previously. The message will include the following information: mm:dd:yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
In Windows notepad, an example of a single log message in an unstructured format is shown below.
Messages from the log
Open the log file in Microsoft Excel to take use of the CSV format, and the result will appear much nicer, as seen below.
Excel spreadsheets with PowerShell logs
Because I needed to preserve a long running history and import data into Excel, I chose the logfile provider over the filesystem provider. The output format makes creating charts and filtering data for reporting a breeze.
Bonus: Runspace Log Querying
Working with runspaces is a more sophisticated function of the PSFramework module. By spinning up threads in a PowerShell runspace, you may run programs in parallel.
PSFramework enables you to look at many logs in real time since you may have several streams of logging operating at the same time in distinct runspaces. Through the utilization of runspaces, these logs may originate from a variety of places. This functionality is highly handy since it allows you to keep a single PowerShell session open while simultaneously executing numerous commands or scripts.
You may use the Runspace option on the Get-PSFMessage command to provide the runspace ID if you know it, as illustrated below.
a2346978-d324-4886-89b8-bd14769be78f Get-PSFMessage -Runspace
Runspace is a difficult concept to understand. If you want to learn more about runspaces, check out this Microsoft DevBlog Series.
A Note from the Author on Using PSFramework in the Real World
For months, I’ve been using the PSFramework module, and it’s helped me improve my maintenance scripts by forcing me to create better code.
It’s pushed me to design better error handling code and make it a habit to set the common ErrorAction parameter to True on cmdlets to generate terminating errors.
I immediately saw the advantages. There was also an ongoing issue that I was ultimately able to resolve utilizing the log file that was provided.
I was getting an issue that only happened when I was running a script with scheduled tasks. When ran manually, the script works well. The problem turned out to be one of credentials and time. The error messages were evident since the error record ID was in the log file, and I was able to narrow it down quickly using tags.
I’ve tried several techniques for creating log files, and this module is by far the most user-friendly.
PSFramework is an excellent module that works well, is dependable, and allows you to have the maximum control over verbose messages.
Summary
Logging should be a significant component of your automated operations, as you’ve learnt throughout this essay. Clear logging requirements, as well as informative and actionable logs and an awareness of logging choices, will go a long way.
Please go through the demonstrations given here if you haven’t used the PSFramework module before. This useful module gives you a variety of choices for logging logs, which will aid troubleshooting, auditing, and security analysis.
Additional Reading
The “write-error log powershell” is a PowerShell script that allows users to write error logs in a file. The script uses the PSFramework module and can be used for any application or service.
Frequently Asked Questions
What is PowerShell module logging?
A: PowerShell module logging is when you use the Set-StrictMode command. This will make your script write out each step of their code as it runs, allowing anyone to see exactly whats happening in a given line of code.
How do you log activity in PowerShell?
A: Some of the methods that you can use to log activity in PowerShell are .NETs Trace.WriteLine, System.Diagnostics.EventLog and using a console window/command line tool such as tail -f
How do you write logs in PowerShell?
A: The simplest way to write logs in PowerShell is as follows.
Write-Log -message log message
$response = Read-Host Enter your name
if ($response -eq ) { Write-Log -message Invalid input, please enter a username. } else { Write-Log -message $username }
Related Tags
- powershell log file
- powershell script logging
- powershell module logging registry
- how to disable powershell logging
- powershell write to log file and console