Dikesh Kumar
Dikesh Kumar

Reputation: 193

Formatting date and time in PowerShell

I want yesterday's date as "MMdd", like "0418" today's date is "0419".

I tried this:

$d = (Get-Date).AddDays(-1) | select -Property Month,Day
$e = $d.Day

$d = $d.Month

$total = "$d" + "$e"

Write-Host $total

But the output was "418".

As you can see, this is a three-letter string, but I want a four-letter one. Because I want to search files they have that format and created a day before.

Upvotes: 2

Views: 273

Answers (1)

Andrew Shepherd
Andrew Shepherd

Reputation: 45222

The date object has a method ToString, which allows you to specify the format:

$d = (Get-Date).AddDays(-1);
$d.ToString("MMdd");

I am calling this on April the 20th, and the output is

0419

See this link for a description of the available date format strings.

Upvotes: 3

Related Questions