How to use the .AddMonths method of Get-Date in Powershell

Viewed 1269

I am writing a simple script that gets the date, gets the date 6 months from now, and copies both of those dates to the clipboard. When run, the script is supposed to copy:

Terminated MM/dd/yy - Delete from AD on MM/dd/yyyy
But it only copies
Terminated MM/dd/yyyy - Delete from AD on

$currentDate = Get-Date -Format "MM/dd/yyyy"
$futureDate = Get-Date.AddMonths(6) -Format "MM/dd/yyyy"
$copyThisText = "Terminated " + $currentDate + " - Delete from AD on " + $futureDate
$copyThisText | clip 
1 Answers

The reason it failed is because once you format a date using -Format "MM/dd/yyyy" it converts that variable to a type of string rather than datetime which then means that the normal datetime methods are no longer available.

For demonstration purposes I have tried to change as little as possible. What I have done below is set the $currentDate and $futureDate without implicitly converting them to strings. I then format them the way you want when you are concatenating the strings in $copyThisText.

This will do what you want.

$currentDate = Get-Date
$futureDate = (Get-Date).AddMonths(6) 
$copyThisText = "Terminated " + $currentDate.tostring("MM/dd/yyyy") + " - Delete from AD on " + $futureDate.tostring("MM/dd/yyyy")
$copyThisText | clip 

Furthermore there are multiple ways to format the strings that could aid in readability of the code. Thanks @Santiago Squarzon for the suggestion -

"Terminated {0:MM/dd/yyyy} - Delete from AD on {1:MM/dd/yyyy}" -f $currentDate, $futureDate
Related