Как преобразовать строку ticks в дату время в power shell

Creating file and folder names based on the current date and time is a common requirement in scripting and automation tasks. PowerShell, a powerful scripting language and shell developed by Microsoft, provides a flexible and easy way to accomplish this. This capability is particularly useful for log files, backups, and any scenario where unique, time-stamped file names are necessary. In this article, we’ll explore how to use PowerShell to generate date and time-based names for files and folders.

PowerShell Get-Date

Ever found yourself in the middle of a scripting task when you suddenly need to add a timestamp? That’s happened to me more times than I can remember! When that occurs, I always rely on my good friend: PowerShell’s Get-Date command. Get-Date is like a dependable sidekick, ready to help you quickly get the current date and time or do calculations whenever you need it.

In this guide, let’s team up to uncover the cool things Get-Date can do in PowerShell. I’ll begin by walking you through the essentials of retrieving dates and times. After that, we’ll tackle some more advanced techniques, such as formatting and calculations.

...Error: "String '638254472943517809' was not recognized as a valid DateTime."

With a bit of help you can tell PowerShell to target the long ctor overload then it has no problems converting a ulong to a long and everything works great!

$ticks = [ulong] 638254472943517809
[datetime]::new($ticks)
Thursday, July 20, 2023 10:54:54 AM

The same would happen if you cast long before casting datetime:

[datetime] [long] [ulong] 638254472943517809
Thursday, July 20, 2023 10:54:54 AM

The Get-Date example is also correct, you’re just missing the parentheses so the conversion from ulong to long happens before the argument being passed to the cmdlet:

Get-Date ([long] $ticks)

[powershell].Assembly. GetType('System.Management.Automation.TypeAccelerators')::Add('ulong', [UInt64])

Introduction to PowerShell Get-Date

PowerShell Get-Date

Before we delve into using the Get-Date cmdlet, let’s first understand the DateTime object in PowerShell. The DateTime object represents a specific date and time and is used to perform various date and time operations in PowerShell. You can retrieve the current date and time using the Get-Date cmdlet. By default, it will display the date and time in the format of the local computer.

Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Month <Int32>] [-Day <Int32>] [-Hour <Int32>] [-Minute <Int32>] [-Second <Int32>] [-Millisecond <Int32>] [-DisplayHint <DisplayHintType>] [-UFormat <String>] [-Format <String>] [<CommonParameters>]

Here’s a basic example:

The cmdlet returns a DateTime object in long-date long-time formats, which can be formatted and manipulated using other PowerShell cmdlets. The DateTime object has several properties, including Year, Month, Day, Hour, Minute, Second, and Millisecond, among others. These properties can be accessed and manipulated using other PowerShell cmdlets.

PowerShell Get-Date


Method 1: Create DateTime Object with Current Date & Time

 = 

This particular example creates a variable named $my_dt that contains the current date and time.

Method 2: Create DateTime Object with Specific Date & Time

 = ( -Date "").ToUniversalTime()

This particular example creates a variable named $my_dt that contains the date January 25, 2024.

Note that we use ToUniversalTime() to display the specific date in universal time rather than in the local time zone of your computer.

Example 1: Create DateTime Object with Current Date & Time in PowerShell

 = 

Как преобразовать строку ticks в дату время в power shell

  • Monday, June 17, 2024 11:21:23 AM

This represents the current date and time when this article is being written.

Example 2: Create DateTime Object with Specific Date & Time in PowerShell

 = ( -Date "").ToUniversalTime()

PowerShell create datetime object with specific time

  • Thursday, January 25, 2024 12:00:00 AM

This represents the date that we specified by using the -Date operator with the Get-Date cmdlet.

Note: You can find the complete documentation for the Get-Date cmdlet in PowerShell here.

How to Use Get-Date and Display Timezone in PowerShell
How to Compare Dates in PowerShell
How to Format a DateTime in PowerShell
How to Calculate Date Difference in PowerShell


The easiest way to format a datetime in PowerShell is to use the ToString() method.

Here is the basic syntax you can use:

 = Get-Date
.ToString("")

This particular example uses Get-Date to save the current date and time in a variable named $mydate, then uses ToString() to format the date using a MM/dd/yyyy format.

  • dd: 2 digit day of the month
  • MM: 2 digit month number
  • YY: 2 digit year number
  • dddd: Full name of day
  • MMMM: Full name of month
  • yyyy: 4 digit year number
  • HH:mm: Time in 24-hour format
  • HH:mm:ss: Time in 24-hour format with seconds
  • HH:mm:ss.fff: Time in 24-hour format with milliseconds
  • hh:mm: Time in 12-hour format
  • hh:mm tt: Time in 12-hour format with AM/PM

Example 1: Format DateTime Using MM/dd/yyyy

 = Get-Date
.ToString("")

Format DateTime in PowerShell

Notice that the datetime is formatted as 03/01/2024.

Example 2: Format DateTime Using MM/dd/yyyy HH:mm:ss

 = Get-Date
.ToString("")

Как преобразовать строку ticks в дату время в power shell

Notice that the datetime is formatted as 03/01/2024 08:38:10.

Example 3: Format DateTime Using MM/dd/yyyy hh:mm tt

 = Get-Date
.ToString("MM/dd/yyyy hh:mm tt")

PowerShell format datetime with AM / PM

Notice that the datetime is formatted as 03/01/2024 08:40 AM.

By using the tt specifier, we are able to add the AM / PM distinction at the end of the datetime.

Note: In this tutorial we only illustrated a few examples of how to format datetimes in PowerShell. Feel free to use any combination of specifiers you would like to format your datetime in the exact way you want.

PowerShell: How to Compare Dates
PowerShell: How to List Files in Directory by Date
PowerShell: Get List of Files Modified After Certain Date
PowerShell: Check if File Has Been Modified in last 24 Hours

Creating a Folder with a Timestamp

Similarly, you can create a directory (folder) with a timestamp in its name by slightly modifying the above script.

$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
New-Item -Path "C:\Backups\Backup_$timestamp" -ItemType "directory"

This creates a new backup folder in the C:\Backups directory, using the current date and time as part of the folder name.

Get-Date with Calculations

PowerShell provides several cmdlets and methods for performing advanced date and time manipulation. Some of these operations include Adding Date, Subtracting Date, and finding the TimeSpan, among others. Here are some examples:

This will display the date and time that is 30 days from now! Similarly, you can add hours to the current time as:

 (Get-Date).AddHours(2).ToString("MM-dd-yyyy HH:mm:ss")

This will display the date and time 2 hours from now in the format of the month-day-year hour:minute:second. Similar to AddDays(), We have methods available for adding Months, Years, Hours, Minutes, etc.:

(get-date).AddDays(5)
(get-date).AddMonths(5)
(get-date).AddYears(5)
(get-date).AddHours(5)
(get-date).AddMinutes(5)
(get-date).AddSeconds(5)

Time Comparison: Let’s say a task was logged with a 48-hour resolution SLA, and you want to calculate time:

$logDate = "2023-08-18 14:00"
$dueDate = ([datetime]$logDate).AddHours(48)
if ((Get-Date) -gt $dueDate) { "SLA breached!"
}

Retrieving yesterday’s date with PowerShell

Sometimes, you may need to retrieve yesterday’s date for various purposes. PowerShell provides a simple method to achieve this using the AddDays() method. To retrieve yesterday’s date, you can subtract one day from the current date:

This will return the date corresponding to yesterday. Similarly, you can get last month using:

$LastMonth = (Get-Date).AddMonths(-1).ToString('MMMM')

Adding or subtracting days from a date in PowerShell

For instance, to add 10 days to a date, you can use the Add-Date cmdlet as shown below:

$date = Get-Date "2022-01-01"
$date = $date.AddDays(10)

In many scenarios, you may need to add or subtract a certain number of days from a given date. PowerShell provides a simple way to accomplish this using the AddDays() and Subtract() methods of the DateTime object. For example, to add 7 days to the current date:

:/>  Как перезагрузить windows по расписанию

Similarly, to subtract 7 days from the current date, use:

As an alternative option, you use the “Subtract()” method of the DateTime object as:

(Get-Date).Subtract([TimeSpan]::FromDays(3))

You can adjust the number of days as per your requirements. Or even minutes: Let’s say 15 min from now!

$FutureTime = (Get-Date).AddMinutes(15)

Find out the Total execution time of a PowerShell Script

Although you can use Measure-Command, and Stopwatch methods to find the script execution time, Here is a simple way to measure the time taken to complete the execution of a PowerShell script:

# Capture the start time
$startTime = Get-Date
# Do some processing
Start-Sleep -Seconds 5
# Capture the end time
$endTime = Get-Date
# Calculate the time difference using New-TimeSpan
$executionDuration = New-TimeSpan -Start $startTime -End $endTime
# Display the execution time
Write-Output "Script took $($executionDuration.TotalMilliseconds) milliseconds to execute."
Write-Output "Script took $($executionDuration.TotalSeconds) seconds to execute."

Best Practices for Using PowerShell Get-Date

  • Use Standard DateTime Formats: When formatting dates and times, it’s best to use standard DateTime formats. These formats are recognized across different platforms and applications, making it easier to share and manipulate data.
  • Use Variables to Store Dates and Times: To make your code more readable and maintainable, it’s best to use variables to store dates and times. This makes it easier to reference the date and time in your code and modify it when necessary.
  • Validate Date Inputs: If your script or function accepts date inputs, always validate them to ensure they are in the correct format. This avoids potential errors or incorrect calculations.
  • Always Handle Time Zones: Consider the Kind property of a [datetime] object (e.g., Local, Utc, Unspecified). If you’re working with date and times from multiple time zones or saving dates for later use, consider converting to UTC time (Universal time coordinate) : (Get-Date).ToUniversalTime()
  • Use [datetime] Type Accelerator for Conversion: When converting strings to date, use the [datetime] type accelerator for clarity and consistency. $date = [datetime]”2021-08-20″
  • Be Mindful of Culture-Specific Settings: Remember that date formats can be culture-specific. Ensure that your scripts can handle different formats, especially if they will be used in different locales.
  • Opt for .NET Methods When Needed: Sometimes, more specific operations on dates (like checking if a year is a leap year) are easier using .NET methods. Don’t shy away from them. E.g., [DateTime]::IsLeapYear((Get-Date).Year)
  • Consistent Naming in Scripts: When using Get-Date in scripts, maintain a consistent naming convention for date variables to enhance readability. E.g., “StartDate”, “EndDate”.

Converting Get-Date to string format in PowerShell

Sometimes, you may need to convert the Get-Date output to a string format for further processing or displaying purposes. PowerShell provides several options for converting Get-Date to a string. One of the commonly used methods is the ToString() method, which allows you to specify the desired format.

(Get-Date).ToString("yyyy-MM-dd HH:mm:ss")

This will convert the current date and time to a string format in the format yyyy-MM-dd HH:mm:ss. You can customize the format specifier to match your requirements, such as displaying the time, including milliseconds, or using different separators.

Get-Date -Format "dd-MM-yyyy"

This converts the date to a specific string format. E.g., 20-08-2021.

Practical Examples of Using PowerShell Get-Date

Let’s look at some practical examples of using PowerShell Get-Date.

Example 1: Password Expiration Reminder Date

$expiryDate = (Get-Date).AddDays(90)
"Your password will expire on $expiryDate."

The command will create a log file with a filename in the format MyLog_20220101_120000.log.

Example 2: Scheduling a Task Time

$trigger = New-ScheduledTaskTrigger -Once -At (Get-Date "2022-01-01 10:00:00")

The command will create a trigger to run the task once at 10:00:00 on January 1st, 2022.

Example 3: Age Calculation

If you need to calculate someone’s age based on their birthdate:

$birthDate = "1990-08-20"
$age = ((Get-Date) - [datetime]$birthDate).Days / 365
[math]::Floor($age)

Example 4: Cleaning up Old Logs

Let’s say you want to delete log files older than 30 days:

$CutOffDate = (Get-Date).AddDays(-30)
Get-ChildItem -Path "C:\Logs" | Where-Object { $_.CreationTime -lt $CutOffDate } | Remove-Item

Example 5: Validating Date Input

$userInput = "2021-07-20"
$inputDate = [datetime]$userInput
$currentDate = Get-Date
If (($currentDate - $inputDate).Days -le 30) { "The date is within the last 30 days."
}

Using the PowerShell Now function

PowerShell offers the Now function, which combines date and time components into a single object. This can be useful for time management tasks that require precise timing. To retrieve the current date and time using “Now”, you simply need to call the function:

[DateTime]::Now
#Output: Monday, August 21, 2023 10:46:02 PM

The output will be in the default format specified by the system’s regional settings.

How to Convert String to Date in PowerShell?

How about the reverse? If you have a string object representation of a date, and you want to convert it to a DateTime object, Here is how you can use the Get-Date cmdlet:

$dateString = "2021-08-21"
$dateObject = Get-Date -Date $dateString
$dateObject
[datetime]::ParseExact("20-08-2021", "dd-MM-yyyy", $null)

This takes the string and converts it into a datetime object.

Getting the Current Date and Time

In PowerShell, you can get the current date and time by using the Get-Date cmdlet. This cmdlet is highly customizable and can be formatted to suit your needs.

Get-Date

Comparing Dates in PowerShell

PowerShell provides several operators and cmdlets for comparing dates and times. You can use the -lt, -le, -eq, -ne, -gt, and -ge operators to compare dates and times.

$date1 = Get-Date "2022-01-01"
$date2 = Get-Date "2022-01-02"
if ($date1 -lt $date2) { "First date is earlier!"
}

PowerShell Get-Date allows you to compare dates easily, enabling you to perform various operations based on date comparisons. The CompareTo() method is particularly useful for this purpose. It returns an integer value indicating the relationship between two dates. Here’s an example:

$date1 = Get-Date "2021-01-01"
$date2 = Get-Date "2022-01-01"
$result = $date1.CompareTo($date2)

In this example, we create two variables, $date1 and $date2, and assign them specific dates. We then use the CompareTo() method to compare $date1 and $date2. The result will be an integer value:

  • -1 if $date1 is earlier than $date
  • 0 if they are equal
  • 1 if $date1 is later than $date2.

You can use this information to conditionally execute code based on date comparisons.

To check if a given date is in the past:

$GivenDate -lt (Get-Date)

Here, $givenDate represents the date you want to compare with the current date. You can modify the comparison operator based on your specific needs.

Creating a File with a Timestamp

To create a file with a name based on the current date and time, you can combine Get-Date with the New-Item cmdlet.

$timestamp = Get-Date -Format "yyyy-MM-dd_HH-mm-ss"
New-Item -Path "C:\Logs\Log_$timestamp.txt" -ItemType "file"

This script creates a new log file with the current date and time as part of its name in the C:\Logs directory.

:/>  «Как создать список документов, хранящихся в указанной папке, и ускорить процесс создания полного списка файлов, полученных из указанной папки, с дополнительной возможностью беспрепятственного переноса указанных данных в электронную таблицу Excel»

Calculating the difference between two dates in PowerShell

At times, you may need to calculate the duration or difference between two dates. PowerShell offers the Subtract() method of the DateTime object to achieve this. For example, to calculate the number of days between two dates:

$startDate = Get-Date -Year 2021 -Month 1 -Day 1
$endDate = Get-Date -Year 2021 -Month 12 -Day 31
$duration = $endDate.Subtract($startDate).Days

Here, $startDate and $endDate represent the two dates between which you want to calculate the difference. The result will be stored in the variable $duration. Instead of “Subtract”, you can use:

$dateStart = Get-Date -Date "2023-01-01"
$dateEnd = Get-Date
$diff = $dateEnd - $dateStart #Alternatively: New-TimeSpan -Start $datestart -End $dateEnd
$diff.Days

PowerShell Get-Date allows you to easily calculate the difference between two dates using the Subtract() method. This method returns a TimeSpan object representing the time difference between two dates. Here’s an example:

$date1 = Get-Date "2021-01-01"
$date2 = Get-Date "2022-01-01"
$diff = $date2.Subtract($date1)
$diff

In this example, we create two variables, $date1 and $date2, and assign them specific dates. We then use the Subtract() method to calculate the difference between $date2 and $date1. The result is a TimeSpan object that represents the duration between the two dates. You can access the Days, Hours, Minutes, Seconds, and other properties of the TimeSpan object to retrieve specific information about the time difference.

difference between two dates

Advanced Formatting Options

PowerShell’s Get-Date -Format supports a wide range of format specifiers, allowing you to customize the date and time format to your exact requirements. For example, if you only need the date for a daily log file, you can format the date without the time.

Get-Date -Format "yyyy-MM-dd"

PowerShell Dates and Times

$exampleDateTime1 =
[] $exampleDateTime2 = 

It is also possible to assign a specific date and time to a variable.

$exampleDateTime1 = -Date "26/08/2023 12:00:00"
[] $exampleDateTime2 = -Date "26/08/2023 12:00:00"

If no formatting is applied, a ‘datetime’ variable can be displayed, for example, in the console, in a similar manner to other variables, such as strings, as shown below, using the ‘Write-Host’ cmdlet.

 $exampleDateTime1
26/08/2023 12:00:00

Often, when the value of a ‘datetime’ variable is used, this isn’t an ideal format. PowerShell allows for a number of different formats to be used.

 "Date: $($exampleDateTime1.ToString('dddd, dd MMMM yyyy'))"
Date: Saturday, 26 August 2023

Similarly, the format of the time portion can be specified.

 "Time: $($exampleDateTime1.ToString('HH:mm'))"
Time: 12:00

Below is a table showing format patterns that can be used when displaying dates and times.

Format
Pattern
Description
dDay of the month as a number from 1 through 31.
ddDay of the month as a number from 01 through 31.
dddThree character abbreviation for the day of the week e.g. Mon for Monday.
ddddFull name for the day of the week e.g. Monday.
hHours, using a 12 hour clock, with no leading zero e.g. 5.
hhHours, using a 12 hour clock, with a leading zero e.g. 05.
HHours, using a 24 hour clock, with no leading zero e.g. 17.
HHHours, using a 24 hour clock, with a leading zero e.g. 20.
mMinutes, with no leading zero e.g. 6.
mmMinutes, with a leading zero e.g. 06.
MMonth as a number, with no leading zero e.g. 3 for March.
MMMonth as a number, with a leading zero e.g. 03 for March.
MMMThree character abbreviation for the month e.g. Mar for March.
MMMMFull name for the month e.g. March.
sSeconds, with no leading zero e.g. 8.
ssSeconds, with a leading zero e.g. 08.
tAbbreviation for time of day, AM and PM e.g. A or P.
ttTime of day e.g. AM or PM.
yYear, without the century and no leading zero e.g. 9.
yyYear, without the century and a leading zero e.g. 09.
yyyyYear, including the century e.g. 2017.

These format patterns can also be used with the ‘Get-Date’ cmdlet, to format the current date and/or time.

 "Today's date is: $(Get-Date -Format 'dd/MM/yyyy')."

As well as being able to format dates and times using the format patterns above, PowerShell also provides a number of properties to access individual components of a date and time, as shown below.

$exampleDateTime1 = -Date "26/08/2023 12:00:00" $exampleDateTime1.Day $exampleDateTime1.DayOfWeek $exampleDateTime1.Month $exampleDateTime1.Year $exampleDateTime1.Hour $exampleDateTime1.Minute $exampleDateTime1.Second

On top of these properties, there are also built in methods for manipulating dates and times, as can be seen below, where one is added to each component of a date and time.

$exampleDateTime1 = -Date "26/08/2023 12:00:00" $exampleDateTime1
$exampleDateTime1 = $exampleDateTime1.AddDays(1)
$exampleDateTime1 = $exampleDateTime1.AddMonths(1)
$exampleDateTime1 = $exampleDateTime1.AddYears(1)
$exampleDateTime1 = $exampleDateTime1.AddHours(1)
$exampleDateTime1 = $exampleDateTime1.AddMinutes(1)
$exampleDateTime1 = $exampleDateTime1.AddSeconds(1) $exampleDateTime1
26/08/2023 12:00:00
27/09/2024 13:01:01

In order to subtract from the various components, a negative value can be used with the above methods, for example minus one to subtract one day.

The properties and methods discussed above are by no means exhaustive. There are many others available.

Formatting the Date and Time

To format the date and time in a specific way, you can use the -Format parameter of the Get-Date cmdlet. PowerShell supports custom date and time formats, allowing you to create strings suitable for file and folder names.

Get-Date -Format "yyyy-MM-dd_HH-mm-ss"

This command will produce a string formatted as 2024-03-01_12-30-45, which is a common format for timestamping files.

Working with Date Variables in PowerShell

In PowerShell, you can assign dates and times to variables and use them in various operations. To assign a date and time to a variable, you can use the PowerShell Get-Date cmdlets, as shown below:

$date = Get-Date "2022-01-01"

Once you have assigned the date and time to a variable, you can use other PowerShell cmdlets to manipulate it. For instance, you can use the AddDays method to add or subtract days from the date. You can also extract the individual components, such as day, month, year, etc., using the properties of the DateTime object. For example, to retrieve the current year:

(Get-Date).Year
#Output: 2021
#More Examples
(Get-Date).DayOfWeek
#Output: Saturday
(Get-Date).DayOfWeek.value__
#Output: 6

PowerShell Get-Date also offers a wide range of methods and properties for working with date and time objects. These allow you to extract specific components, such as the day, month, year, hour, minute, or second, and perform various operations. PowerShell Get-Date also offers a wide range of methods and properties for working with date and time objects. Here are some examples:

  • $date.DayOfWeek returns the day of the week.
  • $date.DayOfYear returns the day of the Year.
  • $date.Month returns the month.
  • $date.Year returns the year.
  • $date.Hour returns the hour.
  • $date.Minute returns the minute.
  • $date.Second returns the second.

By utilizing these properties, you can perform advanced calculations, manipulate specific components, or extract information as needed. Apart from properties there are methods in the DateTime object, such as “IsDaylightSavingTime()” to check if daylight savings time is ON.

Formatting Date and Time in PowerShell

PowerShell provides several ways to format dates and times. You can use the -Format parameter with the Get-Date cmdlet to format the output date and time. The parameter accepts various standard and custom format strings. E.g., the below script gets you the simple date format:

You can supply the format string to get the date in specific format “dd-MMM-yyyy”:

Get-Date -Format "dd-MMM-yyyy" #Output: 21-Aug-2021 Get-Date -Format "MM/dd/yyyy HH:mm K" # Output: 08/21/2023 20:17 +04:00 (with Time zone offset)
Get-Date -Format "hh:mm:ss tt"
#For 24-Hour format, use: Get-Date -Format "HH:mm:ss"

Getting the date without the time using PowerShell Get-Date

In certain scenarios, you may only require the date without the time component. Get-Date allows you to extract the date portion by using the ToString() method with a specified format. For example:

(Get-Date).ToString("dd/MM/yyyy")
#Output: 21/08/2023
(Get-Date).ToString("dddd,dd MMM yyyy")
#Output: Monday,21 Aug 2023

This will return the current date in the format dd/MM/yyyy, without the time component. You can customize the format string according to your preference. You can also use the Get-Date command to retrieve the date and time in different formats. Here is one more example:

Get-Date -Format "MM-dd-yyyy"
#Output: 08-21-2021

This will output the Month number and Day of the month in 2 digits, and the year in a 4-digit format. Alternatively, you can use the parameter -UFormat to specify a custom date and time in UNIX format. The parameter accepts the same format strings as the Microsoft .NET Framework.

Get-Date -UFormat "%Y-%m-%d"
#Output (ISO Format): 2021-08-21

Another way to get the date part from Get-Date cmdlet is using its -DisplayHint parameter.

Get-Date -DisplayHint Date

Use the (Get-Culture).DateTimeFormat cmdlet to get all date time formats of the local computer’s culture settings:

PS C:\> (Get-Culture).DateTimeFormat AMDesignator : AM
Calendar : System.Globalization.GregorianCalendar
DateSeparator : /
FirstDayOfWeek : Sunday
CalendarWeekRule : FirstDay
FullDateTimePattern : dddd, MMMM d, yyyy h:mm:ss tt
LongDatePattern : dddd, MMMM d, yyyy
LongTimePattern : h:mm:ss tt
MonthDayPattern : MMMM d
PMDesignator : PM
RFC1123Pattern : ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
ShortDatePattern : M/d/yyyy
ShortTimePattern : h:mm tt
SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss
TimeSeparator : :
UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z'
YearMonthPattern : MMMM yyyy
AbbreviatedDayNames : {Sun, Mon, Tue, Wed...}
ShortestDayNames : {Su, Mo, Tu, We...}
DayNames : {Sunday, Monday, Tuesday, Wednesday...}
AbbreviatedMonthNames : {Jan, Feb, Mar, Apr...}
MonthNames : {January, February, March, April...}
IsReadOnly : False
NativeCalendarName : Gregorian Calendar
AbbreviatedMonthGenitiveNames : {Jan, Feb, Mar, Apr...}
MonthGenitiveNames : {January, February, March, April...}

Adding the date to a filename using PowerShell

When working with files, it is often useful to append the current date to the filename for better organization. PowerShell makes this task easy using Get-Date. You can use the ToString() method to format the date and then concatenate it with the filename string.

:/>  Как включить dhcp cmd

For example: When troubleshooting systems, log files are often generated. To prevent overwriting and to ensure easy retrieval, you can append the date and time to the filename.

$Filename = "log_" + (Get-Date).ToString("yyyyMMdd_HHmmss") + ".log"

This will create a filename in the format log_yyyyMMdd_HHmmss.log, E.g., “log_20210821_082843.log”. You can adjust the format string as needed.

Here is another way to timestamp filenames:

$LogFile = "C:\Logs\MyLog_$(Get-Date -Format "yyyyMMdd_HHmmss").log"

The command will create a log file with a filename in the format MyLog_20220101_120000.log.

Create a Directory with Year-Month-Day Timestamp:

If you want to create a directory with a timestamp appended to its name, PowerShell is your reliable ally. Here is an example:

#Frame Folder Name with Timestamp
$BackupFolderName = "Backup_" + (Get-Date -Format "yyyy-MM-dd")
#Create a New Folder
New-Item -Path "C:\Backup" -Name $BackupFolderName -ItemType Directory

This creates a folder “Backup_2021-08-21” to the “C:\Backup”.

A Sample PowerShell Script to Create Files and Folders with Date & Time

Here is a sample PowerShell script that will create file and folder with date and time in there names.

# Get the current date and time
$CurrentDate = Get-Date
# Format date and time components
$Year = $CurrentDate.ToString("yyyy")
$Month = $CurrentDate.ToString("MM")
$Day = $CurrentDate.ToString("dd")
$Hour = $CurrentDate.ToString("HH")
$Minute = $CurrentDate.ToString("mm")
$Second = $CurrentDate.ToString("ss")
# Combine date and time components to form a filename
$Filename = "Log_$Year-$Month-$Day" + "_$Hour-$Minute-$Second.txt"
# Create a log file with a timestamp in its name
"Log entry" | Out-File $Filename
# Combine date components to form a directory name for backups
$DirName = "Backup_$Year-$Month-$Day"
# Create a backup directory with a timestamp in its name
New-Item -ItemType Directory -Path $DirName

Save the above script in a file named script.ps1 and execute it.

Create File & Folder Names with Datetime in PowerShell
File & Folder Names with Date/Time

The script will A log file named in the format Log_YYYY-MM-DD_HH-MM-SS.txt will be created. This file will contain the text “Log entry”. Also it will create a directory named in the format Backup_YYYY-MM-DD will also be created in the current working directory.

Getting the current time with PowerShell

In addition to retrieving the current date and time, PowerShell also allows you to extract only the time component. This can be useful in scenarios where you need to perform time-specific operations. To get the current time using Get-Date, you can use the TimeOfDay property:

Get Time of the day

To get just the current time element, you can also use:

 Get-Date -Format "hh:mm:ss tt"

This will return the current time in the format HH:mm:ss AM/PM.

Wrapping up

With the knowledge and skills outlined in this guide, you can confidently use the Get-Date cmdlet to perform various date and time operations in PowerShell. By understanding the basics of PowerShell Get-Date and exploring its various features and functionalities, you can significantly enhance your scripting skills.

How do I convert a date to a string in PowerShell?

How to get only the date from DateTime in PowerShell?

To get only the date from a DateTime object in PowerShell, you can use the ToString() method with a specific date format. Here’s how you can do it:
(Get-Date).ToString("yyyy-MM-dd")

How to get the Date format month name in PowerShell?

Use the ToString() method with a custom format string to get the month name. Here’s an example: (Get-Date).ToString("MMMM")

How do I get the month in PowerShell?

To get just the month, you can use the Month property of the returned DateTime object. Here are the examples:
(Get-Date).Month
(Get-Date).ToString("MMMM")

How do I get the current month and year in PowerShell?

To get the current month and year in PowerShell, you can use the Get-Date cmdlet in the below ways:
(Get-Date).ToString("yyyy-MM")
Get-Date -Format "MMMM-yyyy"

What is the PowerShell operator for date comparison?

How do I add 7 days to a Date in PowerShell?

To add 7 days to a date in PowerShell, you can use the AddDays() method. Here are two ways to do it:
(Get-Date).AddDays(7)
(Get-Date "2021-01-01").AddDays(7)

How to get the year from Date in PowerShell?

To get the year from a date in PowerShell, you can use the Year property of the DateTime object. E.g., (Get-Date).Year .You can use the ToString() method with a custom format string. For example: (Get-Date).ToString("yyyy")

How to get AM and PM in Date format PowerShell?

To get the “AM” or “PM” indicator in the date format in PowerShell, you can use the “tt” format specifier with the ToString() method of the DateTime object. Here’s an example:
(Get-Date).ToString("yyyy-MM-dd tt")

How do I get the current time stamp in PowerShell?

Conclusion

PowerShell offers a powerful and flexible way to work with date and time, making it easy to include timestamps in file and folder names. This is invaluable for creating easily sortable, unique names for logs, backups, and other files that are created as part of automated processes. By mastering the use of the Get-Date cmdlet and its formatting options, you can enhance your PowerShell scripts to handle files and directories more effectively.