(Get-Date).AddDays along with Format switch

We commonly use the switch -Format along with Get-Date commandlet to adjust the date format. However, its not really possible to club date format change along with .adddays() method.

(Get-Date -Format yyyyMMdd).AddDays(x)

This is because of the fact that Format switch will change the type to “STRING” while changing the date format. And .adddays() is a method for the type DateTime.

While the commandlet is executing, Formatting happens first and then trying to use the method .adddays(). Which will fail as expected.

Method invocation failed because [System.String] does not contain a method named ‘AddDays’.

The error message is pretty straight. Method AddDays is not found within [Systems.String]. So the question is how to deal with this? The traditional option is to store the changed date to a variable first and then do the formatting as the second step.

So lets look at some more ways to accomplish in a single line. Possible?

  1. Call the Get-Date command along with adddays method inside Get-Date commandlet with formatting

2. Use method .adddays first and then .ToString

This is simple, but which one is better?

(Get-Date).AddDays(x).ToString(‘yyyyMMdd’) is slightly better as its approximately one millisecond quicker to finish.

Here are some intresting artcles to read on Get-Date and the options around it



Leave a Reply