PowerShell: Create a unique log file name out of date/time


I create log files or transcripts all the time with my PowerShell scripts. I needed a reliable filename with date and time. So I wrote an quick function to format the date and time that easy to read and identify the list of files.

Here it is. Use the function for your purposes. The code includes an example code on how I use the function.

<#
 Function to return current date and time formatted to use log file
 name. 
 How it works: Call the function and use the returned value to 
 create an log file name in your code. 
 E.g., 
 $logfilename = "My-Script-" + (date_time()) + ".log"
 #>
 function date_time()
 {
     return (Get-Date -UFormat "%Y-%m-%d_%I-%M-%S_%p").tostring()
 }


# Example use of function
# Create an log file name and assign to $logfilename variable
 $logfilename = "My-Script-" + (date_time) + ".log"
 
# Display the log file name
 $logfilename

Example file name created by this script:

My-Script-2019-06-12_08-26-30_PM.log

One thought on “PowerShell: Create a unique log file name out of date/time

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s