Get Yesterday’s Date in PowerShell

Get yesterday's date in PowerShell

Using Get-Date Command with AddDays() method

Use the Get -Date command with AddDays() method to get yesterday’s date in PowerShell. Pass -1 to AddDays() to substract one day from current date and time

The simplest way to get yesterday’s date in PowerShell is by using the Get-Date cmdlet with AddDays() method. For example, in the above code, (Get-Date) retrieves the current date and time on the local computer using the Get-Date cmdlet,.AddDays(-1) subtracts one day from the current date using the AddDays method of the DateTime object, and -1 specifies the number of days to subtract, which in this case is one day.

The.ToString('yyyy-MM-dd') formats the resulting DateTime object as a string with the format yyyy-MM-dd. This specifies the year, month, and day in four-digit format, separated by hyphens. The output of this code is displayed using the format yyyy-MM-dd.

Using [DateTime] Command with AddDays() method

Use the [DateTime] command with AddDays() method to get yesterday’s date in PowerShell. Pass -1 to AddDays() to substract one day from current date and time

The[DateTime]::Now command creates a new instance of the DateTime class with the current date and time. TheAddDays(-1) Subtracts one day from the current date and time. ToString('yyyy-MM-dd') Converts the date to a string in the format of yyyy-MM-dd as discussed in the previous code fence.

Using .NET DateTime Object with AddDays() method

Use the.NET DateTime Object with AddDays() to get yesterday’s date in PowerShell. Pass -1 to AddDays() to substract one day from current date and time

Another way to get yesterday’s date in PowerShell is by using the .Net DateTime .NET Framework class.

The above code fence uses the [DateTime]::Today: cmdlet to get the current date with the time set to 12:00:00 midnight. The rest of the code AddDays(-1) and ToString('yyyy-MM-dd') is the same as the previous two blocks of code and displays the output in yyyy-MM-dd.

Considering the above solutions, PowerShell users can automate tasks that require dates and times more efficiently and effectively, such as backup files, recording events, and scheduling tasks.

That’s all about how to get yesterday’s date in PowerShell.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *