1

I need a PowerShell function to add 23 months to the current date, but set the day to the first.

I tried a while loop to subtract the days, but I have had no luck. I have the month part figured out, but I need to set the $current.day to a constant 1.

function Update-Date {
    $current = Get-Date
    $current.AddMonths(11)
    $current.AddYears(1)
    $current.Day(1)
}

2 Answers 2

5

The Get-Date cmdlet can adjust components of a (copy of a) specified date via its -Day, -Month and -Year parameters (and analogously for the time portion), so try the following:

Get-Date -Day 1 (Get-Date).Date.AddMonths(23)

Note the use of .Date, which removes the time-of-day portion from the date.

Wrapped in your function (renamed for consistency with PowerShell's naming conventions; note that the function outputs the resulting date):

function Get-UpdateDate { Get-Date -Day 1 (Get-Date).Date.AddMonths(23) }
Sign up to request clarification or add additional context in comments.

Comments

1

There are better and more concise ways to do it (see mklement0's answer), but as a learning opportunity, try this:

$val = Update-Date
Write-Host $val

function Update-Date {
    $current = Get-Date
    $current = $current.AddMonths(11)
    $current = $current.AddYears(1)
    $current = $current.AddDays(-($current.Day) + 1)
    return $current
}

Notice that the AddMonths, AddYears, AddDays, etc. do not modify the original Date, but instead return a new one. You need to store it each time and then perform the next operation. Rather than looping, you can just subtract the current day of the month and add 1 back to get it back to the 1st of the month. I added a return statement and code to output it to the screen, which you can ignore if not needed.

5 Comments

That's good information about [System.DateTime], but I suggest using neither Write-Host (just use $val to output to the success stream - as opposed to writing directly to the host (terminal)) nor return (similarly, just use $current to output the value), so that this doesn't turn into a PowerShell anti-learning opportunity.
well, technically there's nothing wrong with doing return $current its just not really powershellish
@4c74356b41: That it's not "powershellish" is precisely my point: There's also nothing technically wrong with using Write-Host, but using it is probably based on a misconception about how output in PowerShell works - as is the use of return, even though its use is benign. As currently written, the code reinforces frequent misconceptions about PowerShell.
but I wouldn't go as far as calling it anti-learning (talking about return)
Feel free to edit it as I am no expert at PowerShell. I simply write it and test and if it works then I call it good. This is a learning opportunity for me as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.