Powershell – I can create folders with a future date label, but the year is not changing

user201727 asked:

So, I use Powershell to archive user directories, after a user has left. We keep the archive for 6 months before we delete it. The script is supposed to label the archived folder as “DeleteAfter-(6 months from now)-(username)”.
This is all working except for the year. That is to say, the folder label has the year in it, but it does not change if the year changes. Archive folders that are being created now (Dec 2013) are not getting labeled with “2014”, but are instead still getting “2013”.

Here’s a snippet of the date code I am using:

#Operator Input Variable.
$termeduser = read-host "What is the username?"

#Folder name and date variables.
$sixmonths  = (Get-Date) - (New-TimeSpan -days 180)            
$sixmonths  = Get-Date $sixmonths -format "yyyy-MM-dd"                       
$FolderName = "(server)TerminatedEmployeeArchivesDeleteAfter-$sixmonths-$termeduser" 

#Create archive folder            
New-Item -path $FolderName -type Directory

What do I need to add in order to get the year to “flip” to the next?

Thanks!

My answer:


You’re subtracting 180 days instead of adding 180 days:

$sixmonths  = (Get-Date) - (New-TimeSpan -days 180)

Try this instead:

$sixmonths  = (Get-Date) + (New-TimeSpan -days 180)

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.