PowerShell Get-Date Add Days [With Examples]

In this PowerShell tutorial, I will explain how to work with PowerShell Get-Date Add Days, like how to with Get-Date is AddDays, which, as the name suggests, allows you to add (or subtract) days from a given date.

In PowerShell, the Get-Date cmdlet paired with the AddDays method allows you to add or subtract days from a given date easily. For example, to get a date 5 days in the future, you would use (Get-Date).AddDays(5), and to get a date 5 days in the past, you would use (Get-Date).AddDays(-5).

PowerShell Get-Date Add Days

The simplest use of PoweShell Get-Date is to retrieve the current date and time:

Get-Date

This command will return the current system date and time. If you only need the current date without the time, you can format the output like so:

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

Now, let’s look at the AddDays method. This method is used to add a specified number of days to the date object. You can also pass a negative number to subtract days.

Here’s a basic example:

(Get-Date).AddDays(10)

This PowerShell command will give you the date that is 10 days from today. Check out the screenshot below for the output:

PowerShell Get-Date Add Days

Here is another example.

Let’s say you need to calculate the date that is 30 days in the past from the current date for a report or a log file. Here’s how you would do it:

$ThirtyDaysAgo = (Get-Date).AddDays(-30)
Write-Host "The date 30 days ago was: $ThirtyDaysAgo"

This script assigns the date 30 days ago to the variable $ThirtyDaysAgo and then prints it out.

Often, you’ll want to format the output date in a specific way. For example, if you need the date in a yyyyMMdd format, you can use the ToString method to format it in PowerShell:

$FormattedDate = (Get-Date).AddDays(-30).ToString("yyyyMMdd")
Write-Host "The formatted date 30 days ago was: $FormattedDate"

This PowerShell command will output the date 30 days ago in the yyyyMMdd format.

Conclusion

The Get-Date cmdlet in PowerShell is a powerful tool for working with dates and times. The AddDays method is just one of the many methods available to manipulate date objects easily.

I have explained here how to work with Get-Date Add Days in PowerShell with examples.

You may also like:

>