Как преобразовать в шестинственное значение в дату в powershell

Time-base One-Time Password Algorithm (RFC 6238)

This is an implementation of the RFC 6238 Time-Based One-Time Password Algorithm draft based upon the HMAC-based One-Time Password (HOTP) algorithm (RFC 4226). This is a time based variant of the HOTP algorithm providing short-lived OTP values.

Version: 1.0

Author: Jon Friesen

Creation Date: May 7, 2015

Purpose/Change: Provide an easy way of generating OTPs

Write-Host $binary

Write-Host $chunk

Write-Host $hexChunk

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.

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


Often you may want to convert a Unix timestamp to a readable datetime in PowerShell.

This particular example will convert the Unix timestamp stored in the variable named $my_unix_time to a readable datetime.

Note that PowerShell will display the output in UTC in a 24-hour format. By using ToLocalTime() we are able to cover the resulting datetime to the local time on our machine.

Also note you could also use the function FromUnixTimeMilliseconds to convert a Unix time stored in milliseconds to a readable datetime.

Suppose that we would like to convert the Unix timestamp 1667614523 into a readable datetime.

PowerShell convert unix timestamp to datetime

Note that you can specify whatever format you would like to use within the ToString() method to instead display the resulting datetime in a different format.

PowerShell convert unix timestamp to date with specific format

Feel free to use whatever datetime format you would like within the ToString() method.

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

How do i use Powershell to convert the Hex value :1699910580 to this format ? Tuesday, February 22, 2024 5:38:28 PM (UTC)


That’s not a hex date, it’s a Unix timestamp




further to this reply some information to look at is all the date/time stuff in powershell

there is also A nice module ConvertTime that does this well




I tried the get-date with the above value, seems not today, it shows Monday, January 1, 0001 12:02:49 AM




you cant use the value directly, you need to convert it (new-timespan being the likely suspect)




u/DesertGoldfish avatar


Na, you can. You just have to:

(Get-Date $beginningOfEpochTime).AddSeconds(169991....)




Get-Date -UnixtimeSeconds 1699910580

when i got to registry , it shows Hex thought was Hex. thanks to point out




u/illsk1lls avatar


i was just looking for the 2024 and didnt see a 1st and 3rd matching set, like 🤔







u/blooping_blooper avatar


to convert unix timestamps use the System.DateTimeOffset type from .NET:

DateTime : 11/13/2023 9:23:00 PM

Monday, November 13, 2023 9:23:00 PM




thank you , it works !




u/OPconfused avatar


I believe it’s just Get-Date -UnixtimeSeconds 1699910580, but it doesn’t result in Feb 22, 2024.

Actually I think that’s timezone dependent, but you could add the -AsUTC flag if you needed it in UTC: Get-Date -UnixtimeSeconds 1699910580 -AsUTC







u/blooping_blooper avatar


The -UnixTimeSeconds parameter isn’t available in Windows PowerShell, u/OPconfused is likely using PowerShell 7 which does have it




u/OPconfused avatar





u/OPconfused avatar


My bad, I have the updated powershell version and didn’t realize it was a new parameter.




:/>  Ян давид наркевич разработчик

u/blooping_blooper avatar





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.

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.

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.

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

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.

:/>  Вкладка «Дополнительные параметры WINS» для IPv4

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”.

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...}

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.

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.

:/>  Программисты из Symantec нашли эффективный и простой метод борьбы с вирусом Petya

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.

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?

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:

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."

Оставьте комментарий