{"id":206,"date":"2021-02-26T04:15:49","date_gmt":"2021-02-26T12:15:49","guid":{"rendered":"https:\/\/devblogs.microsoft.com\/powershell-community\/?p=206"},"modified":"2021-02-27T09:33:02","modified_gmt":"2021-02-27T17:33:02","slug":"getting-yesterdays-date","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/powershell-community\/getting-yesterdays-date\/","title":{"rendered":"Getting Yesterday&#8217;s Date"},"content":{"rendered":"<p><strong>Q:<\/strong> How can I get yesterday&#8217;s date?<\/p>\n<p><strong>A:<\/strong> You can use a combination of the <code>Get-Date<\/code> cmdlet and .NET Time\/Date methods.<\/p>\n<p>First, let&#8217;s look at dates in PowerShell and .NET Then we can look at how to calculate yesterday and use that in your scripts.<\/p>\n<h2>Dates in PowerShell<\/h2>\n<p>Let&#8217;s start by looking at how you can deal with dates and times. As you probably know, PowerShell contains the <code>Get-Date<\/code> cmdlet. This cmdlet returns a .NET <strong>System.DateTime<\/strong> object.<\/p>\n<p>Using the <code>Get-Date<\/code> cmdlet, you can get any date and time, and either display it or store it in a variable. To get today&#8217;s date. you could do this:<\/p>\n<pre><code class=\"powershell-console\">PS C:&gt; # Get the current date\nPS C:&gt; Get-Date\n08 January 2021 11:24:46\n\n# Store the date in a variable\n$Now = Get-Date\n$Now\n08 January 2021 11:24:47\n<\/code><\/pre>\n<p>As mentioned, the <code>Get-Date<\/code> cmdlet returns an object whose type is <strong>System.DateTime<\/strong>. This .NET structure provides a rich set of properties and methods to help you manipulate the date\/time object. See the <a href=\"https:\/\/docs.microsoft.com\/dotnet\/api\/system.datetime\">System.DateTime documentation<\/a> for more details on this structure. A date and time object contains both a date and a time. This means you can create an object with just a date or just a time, or both, which gives you huge flexibility in handling dates and times.<\/p>\n<p>If you run <code>Get-Date<\/code> and specify no parameters, the cmdlet returns the current date and time. There are several parameters you can specify that allow you to create an object for a particular date, like this:<\/p>\n<pre><code class=\"powershell-console\">PS C:&gt; # Using the -Date Parameter and a date string\nPS C:&gt; Get-Date -Date '1 August 1942'\n01 August 1942 00:00:00\n\n# Using the -Month, Day, Year to be specific and avoid parsing\nPS C:&gt; Get-Date -Month 8 -Day 1 -Year 1942 -Hour 0 -Minute 0 -Second 0\n01 August 1942 00:00:00\n<\/code><\/pre>\n<p>You can see the other features of <code>Get-Date<\/code> to help get the date in the exact format you need, see the <a href=\"https:\/\/docs.microsoft.com\/powershell\/module\/microsoft.powershell.utility\/get-date?view=powershell-7.1\"><code>Get-Date<\/code> help information<\/a>.<\/p>\n<h2>Obtaining Yesterday&#8217;s Date<\/h2>\n<p>So as you can see, you can use <code>Get-Date<\/code> to return a specific date\/time. So how do you get yesterday&#8217;s date &#8211; or the date or last month or last year? The trick here is to use the object returned from <code>Get-Date<\/code>. The object has a type of <code>System.DateTime<\/code> which contains a number of methods allowing you to add increments of time &#8211; a month, a day, etc to the object.<\/p>\n<p>To get yesterday&#8217;s date (or tomorrow&#8217;s) you create a date and time object for today using <code>Get-Date<\/code> with no parameters. Then you use the <code>AddDays()<\/code> method to add\/subtract some number of days, like this:<\/p>\n<pre><code class=\"powershell-console\">PS C:&gt; # Get today's Date\nPS C:&gt; $Today     = Get-Date\nPS C:&gt; $Yesterday = $Today.AddDays(-1)\nPS C:&gt; $Yesterday\n19 February 2021 12:13:51\n\nPS C:&gt; # Or more simply\nPS C:&gt; $Yesterday = (Get-Date).AddDays(-1)\nPS C:&gt; $Yesterday\n19 February 2021 12:13:52\n\nPS C:&gt; # Get tomorrow's date\nPS C:&gt; $Tomorrow  = (Get-Date).AddDays(1)\nPS C:&gt; $Tomorrow\n21 February 2021 12:13:54\n<\/code><\/pre>\n<p>It is worth noting that a <code>System.DateTime<\/code> object is immutable. This means you can not change property values after you create the object. If you use any of the <code>Add<\/code> methods, .NET returns a new object with updated property values.<\/p>\n<h2>Using Yesterday&#8217;s Date<\/h2>\n<p>There are a variety use cases for getting a date in the past (or the future), including:<\/p>\n<ul>\n<li>Identifying files that are older\/younger than a day\/month\/etc ago<\/li>\n<li>Determining which AD Users have not logged on in the last week<\/li>\n<li>Creating a file name for a file representing last weeks information.<\/li>\n<\/ul>\n<p>Here are some examples:<\/p>\n<pre><code class=\"powershell-console\">PS C:&gt; # Finding files newer than yesterday\nPS C:&gt; $Yesterday = (Get-Date).AddDays(-1)\nPS C:&gt; Get-ChildItem | Where-Object LastAccessTime -gt $Yesterday\n\n    Directory: C:\n\nMode                 LastWriteTime         Length Name\n----                 -------------         ------ ----\n-a---          20\/02\/2021    14:20          11041 GratefulDead Show List.txt\n\nPS C:&gt; # Getting users who have logged on in the past day\nPS C:&gt; Get-ADUser -Filter * -Property LastLogonDate | Where-Object LastlogonDate -gt $Yesterday\n\nDistinguishedName : CN=Administrator,CN=Users,DC=cookham,DC=net\nEnabled           : True\nGivenName         : Jerry\nLastLogonDate     : 20\/02\/2021 04:20:42\nName              : Jerry Garcia\nObjectClass       : user\nObjectGUID        : ae31ca0d-3f01-4eb4-8593-b1d79c71f912\nSamAccountName    : JerryG\nSID               : S-1-5-21-2550804810-443649076-1856842782-500\nSurname           : Garcia\n\n# Creating a file with yesterday's date\nPS C:&gt; # Creating a file with today's date\nPS C:&gt; $Yesterday     = (Get-Date).AddDays(-1).ToString() -replace '\/','-'\nPS C:&gt; $YesterdayDate = ($Yesterday -split ' ')[0]\nPS C:&gt; $YesterdayFN   = \"Results for $YesterdayDate.Txt\"\nPS C:&gt; \nPS C:&gt; New-Item -Path C:Results -Name  $YesterdayFN -ItemType File\n\nDirectory: C:Results\n\nMode                 LastWriteTime         Length Name\n----                 -------------         ------ ----\n-a---          20\/02\/2021    12:56              0 Results for 19-02-2021.Txt\n<\/code><\/pre>\n<p>In that last example, you need to do a bit of manipulation of the date\/time returned by <code>Get-Date<\/code> in order to get a filename that Windows accepts. This manipulation is needed because <code>Get-Date<\/code> returns a string that contains the &#8220;\/&#8221; character <code>New-Item<\/code> views as a path character. You use the <code>-Replace<\/code> operator to replace the &#8220;\/&#8221; character with a &#8220;-&#8220;. Additionally, after performing the replacement, you end up with an (unneeded) time value. You can use the <code>-Split<\/code> operator to pull out just the date, which is what you want for the file name. Once you do get the date, you can create you can create a file name for the file.<\/p>\n<p>Another way to generate the file name based on <code>Get-Date<\/code> would be to use the <strong>ToString()<\/strong> method and specify the exact output you want, like this:<\/p>\n<pre><code class=\"powershell\">$YesterdayDate = (Get-Date).AddDays(-1).ToString('yyyy-MM-dd')         \n$YesterdayFN   = \"Results for $YesterdayDate.Txt\"\n<\/code><\/pre>\n<p>Another point worth making is that Windows tries to display dates in a culture-aware way. <code>Get-Date<\/code> does a fairly good job in most cases of converting a date string into the date you wanted. But if you want a specific result, using <strong>ToString()<\/strong> and a date format string is possibly better &#8211; and fewer lines of code.<\/p>\n<p>Needless to say, you could do all those file name manipulations operations as a one-liner. I leave that as an exercise for you!<\/p>\n<h2>Summary<\/h2>\n<p>.NET provides a rich date and time structure (<code>System.DateTime<\/code>). This structure contains a number of properties such the day, month, hour, millisecond for a given date\/time. You also get a wide range of methods that enable you to manipulate dates by adding or subtracting hours, days, etc. You can use <code>Get-Date<\/code> cmdlet to get the current date\/time or an object for a specific date\/time. Get-Date returns an object of System.DateTime. You use the methods of the <code>System.DateTime<\/code> structure to get relative dates, such as yesterday, last month or 2 years 42 days, and 32 milliseconds.<\/p>\n<h2>Tip of the Hat<\/h2>\n<p>This article is based on an earlier Scripting Guys blog article at <a href=\"https:\/\/devblogs.microsoft.com\/scripting\/how-can-i-get-yesterdays-date\">How can I get yesterday&#8217;s date?<\/a>. Not sure who wrote it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Q: How can I get yesterday&#8217;s date? A: You can use a combination of the Get-Date cmdlet and .NET Time\/Date methods. First, let&#8217;s look at dates in PowerShell and .NET Then we can look at how to calculate yesterday and use that in your scripts. Dates in PowerShell Let&#8217;s start by looking at how you [&hellip;]<\/p>\n","protected":false},"author":4034,"featured_media":77,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[13],"tags":[7,8],"class_list":["post-206","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-powershell","tag-net","tag-scripting-guys-update"],"acf":[],"blog_post_summary":"<p>Q: How can I get yesterday&#8217;s date? A: You can use a combination of the Get-Date cmdlet and .NET Time\/Date methods. First, let&#8217;s look at dates in PowerShell and .NET Then we can look at how to calculate yesterday and use that in your scripts. Dates in PowerShell Let&#8217;s start by looking at how you [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/posts\/206","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/users\/4034"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/comments?post=206"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/posts\/206\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/media\/77"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/media?parent=206"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/categories?post=206"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/powershell-community\/wp-json\/wp\/v2\/tags?post=206"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}