How to Use Get-Date in PowerShell: Syntax and Examples
Use the
Get-Date cmdlet in PowerShell to get the current date and time or format dates. You can customize output with parameters like -Format to display dates in different styles.Syntax
The basic syntax of Get-Date is simple and flexible:
Get-Date: Returns the current date and time.Get-Date -Format <string>: Formats the date/time output using a format string.Get-Date -Date <datetime>: Converts or formats a specific date.
powershell
Get-Date [-Date <DateTime>] [-Format <string>] [-UFormat <string>] [<CommonParameters>]
Example
This example shows how to get the current date and time, and how to format it as a short date string.
powershell
Get-Date Get-Date -Format 'yyyy-MM-dd' Get-Date -Format 'dddd, MMMM dd, yyyy HH:mm:ss'
Output
Monday, June 10, 2024 14:30:45
2024-06-10
Monday, June 10, 2024 14:30:45
Common Pitfalls
Common mistakes include using incorrect format strings or expecting Get-Date to modify system time (it only retrieves or formats dates).
Also, using single quotes around format strings is important to avoid variable expansion.
powershell
Get-Date -Format yyyy-MM-dd # Wrong: missing quotes can cause errors
Get-Date -Format 'yyyy-MM-dd' # Correct: quotes ensure proper format stringQuick Reference
| Parameter | Description | Example |
|---|---|---|
| -Format | Formats the output date/time | Get-Date -Format 'MM/dd/yyyy' |
| -Date | Specifies a date/time to format | Get-Date -Date '2024-01-01' |
| -UFormat | Uses Unix-style format strings | Get-Date -UFormat '%Y-%m-%d' |
Key Takeaways
Use
Get-Date to get the current date and time in PowerShell.Customize output with the
-Format parameter using format strings in quotes.Avoid missing quotes around format strings to prevent errors.
Get-Date does not change system time; it only retrieves or formats dates.Use
-Date to format specific dates, not just the current date.