EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Logging
Secondary Sidebar
PowerShell Tutorial
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

PowerShell Logging

PowerShell Logging

Introduction to PowerShell Logging

It is very important for programmers to have logging enabled in their scripts as it will help in troubleshooting during unexpected behavior of the script. Logging is the mechanism of capturing the error message or exception, but it is also helpful in identifying the point until the script has been executed. Sometimes, if a script is working only for a few values and not working for others, then if logging is enabled, it will be easy for the programmer to narrow the issue and fix it. PowerShell provides various methods of logging, which will be covered in detail in this article. PowerShell provides three types of logging such as Module logging, Script block logging, and transcription logging.

Prerequisites to enable enhanced PowerShell Logging

For Windows 10, enhanced PowerShell logging is automatically supported.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

For windows 7,8,2008,2012 with PowerShell v5.0, the following components are required

  • .Net 4.5
  • WMF (4.0/5.0)

For windows 7,8,2008,2012 with PowerShell v4.0, the following components are required

  • .Net 4.5
  • WMF (4.0)

1. Logging Configuration

Before trying to log errors in a script, it is important to enable them in the group policy. Below are the steps

Local Group Policy EditoràAdministrative TemplatesàWindows ComponentsàWindows PowerShell. In that, we need to enable Turn on Module Logging, turn on PowerShell Script Block Logging and Turn on PowerShell Transcription.

2. Module Logging

Module logging records pipeline details such as variable initialization and command invocations as the script executes. It will record samples of script and data that is formatted to be sent as output. In addition, it will capture the logging that may be missed by other types but may fail to capture certain commands. This type of logging event is written under the 4103-event id.

3. Script Block Logging

This is used to capture logs for all the scripts and commands. This is used to determine the mode of attack from an external attacker. Even the decoded commands are also captured and logged. This logging events are recorded under the event id-4104. If the logs exceed the specified limit, it is fragmented into multiple files and captured. From PowerShell 5.0, script blocking is automatically enabled if the script contains certain pre-defined commands or scripting techniques that may be prone to attack. These are logged under the warning level unless script blocking logging is disabled purposefully. This will capture all activity and not just suspicious activity. The non-suspicious activities will be logged under event id 4104 but either as verbose or as information levels.

4. Transcription Logging

If transaction logging is enabled, a record is created for each session, including each input and output command that is present in that session. These are written to a text file along with timestamp and metadata. They are automatically named, starting with PowerShell_transcript. The default location to which the files are written is the user’s document folder; this can be changed if needed. The best place to store them is to a network drive so that the attackers can’t access them easily. The size of the file is very less and then can be reviewed using any standard tool.  The appropriate logging mechanism has to be enabled in the Local Group Policy editor or by setting their value in the registry.

5. Splitting huge log files to smaller files

Sometimes, the log file generated may be huge in size. This may hamper the debugging process. In this scenario, it will be helpful if we can split the single log file into smaller files. The below script will help in achieving this. The script first identifies the source file that needs to be split. It then asks for the destination folder where the new split log files are to be saved. Next, the script prompts the user for the number of lines that should be present in each log file. Once that is done, the new log files are generated.

Input:

Write-Host "Welcome to the demo of Split a large log file into smaller files"
$lc = 0
$fn = 1
# Getting the source log file
$source = Read-Host "Enter the log file path"
# Getting the destination where the smaller log files will be saved
$destination = Read-Host "Enter the destination path"
Write-Host "The total number of lines is being calculated ..... "
Get-Content $source | Measure-Object | ForEach-Object { $sourcelc = $_.Count }
#total number of lines in source file
Write-Host " total number of lines present is  "  $sourcelc
# size of each destination file
$destfilesize = Read-Host "Number of lines to be present in each file"
$maxsize = [int]$destfilesize
Write-Host File is $source - destination is $destination - new file line count will be $destfilesize
$content = get-content $source | % {
Add-Content $destination\splitlog$fn.txt "$_"
$lc ++
If ($lc -eq $maxsize) {
$fn++
$lc = 0
}
}
Write-Host "The new number of smaller files generated is " $fn
Write-Host "Please check the for the files in" $destination

Before running the script, the number of files in the source directory

Before running the script

Output:

PowerShell Logging output 1

After running the script, the number of files in the directory

After running the script

Input:

Write-Host "Welcome to logging example"
Write-Host "Writing success message to console"
for($i=0; $i -le 10; $i++)
{
Write-Host "the value is "$i
}
Write-Host "Demo of writing log to a text file"
for($i=0; $i -le 10; $i++)
{
$i |Out-File -FilePath C:\Vignesh\TestLog\test.txt -Append
}
Write-Host "The logging is done to the file.Please check"

Output:

PowerShell Logging output 2

Conclusion

Thus, the article covered in detail about logging in PowerShell. It explained in detail the various types of logging available and the use of each logging mechanism. The article has explained with an example on how a large log file can be split into smaller log files. It also explained how logging can be done to a file or a console. Logging is one of the best practices to be followed during scripting, as it makes life easier whenever something unusual happens. The best way to learn more about this is to write sample scripts and execute them.

Recommended Articles

This is a guide to PowerShell Logging. Here we discuss the various types of PowerShell Logging that are available and the use of each logging mechanism. You may also have a look at the following articles to learn more –

  1. PowerShell Convert to String
  2. PowerShell Get-Item
  3. PowerShell ForEach Object
  4. PowerShell Alias
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more