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
 How it works: Call the function and use the returned value to 
 create an log file name in your code. 
 $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

Example file name created by this script:


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

  1. Pingback: (Ver 2) PowerShell: Create Unique Log File Name out of Date & Time – Anand, the Architect

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