(Ver 2) PowerShell: Create Unique Log File Name out of Date & Time


I have blogged to create a log file name in PowerShell, so we can create unique readable file names to store data or logs: https://anandthearchitect.com/2019/06/13/powershell-create-a-unique-log-file-name-out-of-date-time/

Now I have an better idea of generating file name with slightly different idea (since I found out GetDateTimeFormats() function in returned object from Get-Date cmdlet).

Here is the function that returns the valid date time format to form a log file name:

Function Date_Time {
Return ((Get-Date).GetDateTimeFormats())[44].Replace('/','-').Replace(' ','_').Replace(':','-')
}

Here is how you use the function:

PS E:> "Customer-Data-" + (Date_Time) + ".csv"
Customer-Data-8-29-2019_08-06_PM.csv

You may have your own date format in the file name. To find out the list of available date/time display formats, run this command:

$i=0 ;  (Get-Date).GetDateTimeFormats() | % { Write-Host $i $_  ; ++$i}

It list the all the formats with the item number (see below). Find the display format you want, note down the item/index number & use it with the above function.

PS E:> $i=0 ;  (Get-Date).GetDateTimeFormats() | % { Write-Host $i $_  ; ++$i}

0 8/29/2019
1 8/29/19
2 08/29/19
3 08/29/2019
4 19/08/29
5 2019-08-29
6 29-Aug-19
7 Thursday, August 29, 2019
8 August 29, 2019
9 Thursday, 29 August, 2019
10 29 August, 2019
11 Thursday, August 29, 2019 7:59 PM
12 Thursday, August 29, 2019 07:59 PM
13 Thursday, August 29, 2019 19:59
14 Thursday, August 29, 2019 19:59
15 August 29, 2019 7:59 PM
16 August 29, 2019 07:59 PM
17 August 29, 2019 19:59
18 August 29, 2019 19:59
19 Thursday, 29 August, 2019 7:59 PM
20 Thursday, 29 August, 2019 07:59 PM
21 Thursday, 29 August, 2019 19:59
22 Thursday, 29 August, 2019 19:59
23 29 August, 2019 7:59 PM
24 29 August, 2019 07:59 PM
25 29 August, 2019 19:59
26 29 August, 2019 19:59
27 Thursday, August 29, 2019 7:59:36 PM
28 Thursday, August 29, 2019 07:59:36 PM
29 Thursday, August 29, 2019 19:59:36
30 Thursday, August 29, 2019 19:59:36
31 August 29, 2019 7:59:36 PM
32 August 29, 2019 07:59:36 PM
33 August 29, 2019 19:59:36
34 August 29, 2019 19:59:36
35 Thursday, 29 August, 2019 7:59:36 PM
36 Thursday, 29 August, 2019 07:59:36 PM
37 Thursday, 29 August, 2019 19:59:36
38 Thursday, 29 August, 2019 19:59:36
39 29 August, 2019 7:59:36 PM
40 29 August, 2019 07:59:36 PM
41 29 August, 2019 19:59:36
42 29 August, 2019 19:59:36
43 8/29/2019 7:59 PM
44 8/29/2019 07:59 PM
45 8/29/2019 19:59

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 )

Facebook photo

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

Connecting to %s