PowerShell provides a lot of tools and commands to monitor and manage logs on Windows systems. The
New-Item cmdlet in PowerShell is used to create a log file with the date and time in their name.
Using the date and time in the log file helps to easily locate logs for specific periods or manage and organized log files based on their creation date and time.
In this article, we will discuss how to create a log file with a date in PowerShell to manage and organized log files.
Construct a Log File Name with the Date and Time
Use the Get-Date cmdlet in PowerShell to get the current date and time and include it in the log file name.
$currentDate = Get-Date -Format "yyyyMMdd_HHmmss" $logFileName = "aduser_backup_$currentDate.log"
In the above PowerShell script, the GetDate cmdlet retrieves the system’s date and time and formats and stores it in the
$currentDate variable. Later, we used the current date and time in a log file name by appending the
The output of the above PowerShell script generates a log file name with the format “aduser_backup_yyyyMMdd_HHmmss” :
Create a Log File with the Date Time
Use the New-Item cmdlet in PowerShell to create a file in the specified directory.
# Get the current date in format $currentDate = Get-Date -Format "yyyyMMdd_HHmmss" # Construct log file with date time $logFileName = "aduser_backup_$currentDate.log" # Specify log file folder path $logFilePath = "D:\PS\$logFileName" # Use New-Item to create a file New-Item -Path $logFilePath -ItemType File
In the above PowerShell script, the
$logFileName variable contains the log file with the date and time. The New-Item cmdlet uses the
-Path parameter to specify the log file folder path to store the log file and uses -ItemType as a File to create a log file with the date and time in the folder.
Cool Tip: How to move files and rename with date in PowerShell!
Writing to the Log File
Use the Add-Content cmdlet in PowerShell to add or appends the content to the log file.
$Message = "Ad users backup successfully completed on 2023-04-09 10:02:24" Add-Content -Path $logFilePath -Value $Message
In the above PowerShell script, the Add-Content command uses the
-Path parameter to specify the location of the log file to write a log message to it.
The output of the above script writes a message to the newly created log file.
Cool Tip: How to write the date and time to a file in PowerShell!
I hope the above article on how to create a log file with the date and time in PowerShell is helpful to you.
Using the Get-Date, New-Item, and Add-Content cmdlets, you can efficiently manage the logs on your Windows system.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.