PowerShell assign current date and time to a variable

I pieced together a PowerShell script that is triggered (via Task Scheduler) every time the computer restarts.

The script will do the following:
1. Find a csv file located in a specific directory
2. Rename the file by appending a time/date stamp to the end
3. Move that file into an archive folder

During the day a software application automatically creates a new csv file. So next time the computer reboots, it repeats the steps above.

4. Final step - the script also looks in the archive folder and deletes any files which are > 7 days old.

Sometimes (not all the time) when the computer restarts and the script runs, it completes steps 1 and 2 but not step 3.
And so what this means is the csv file is renamed but the script did NOT move it into the archive folder.

I open the script in PowerShell ISE and run the script manually and I see the reason why:
A file with that name already exists in the archive folder.

How can that happen if the file name is always dynamically renamed using a date/time stamp (down to the second).

Turns out the variable which is assigned the value of Get-Date is not updated.
It still contains the old time.

Why does this happen if the very first thing I do in my PowerShell script is this:
$rightNow = Get-Date

I know it's not best practice to assign the current date and time to a variable and obviously the variable is not going to update itself as every second goes by. That's fine. I don't need it to. What I DO expect it to do is grab the current date and time (at the time this line of code runs) and assign it to my variable called $rightNow.

For some reason the variable is not getting updated.
Why does this happen? What's the best way for me to quickly grab the current date and time (down to the second) and use it as part of a file name?

Here is my current script:

$source = "C:\Logs"
$destination = "C:\Logs\archive"
$old = 7
$rightNow = Get-Date

# delete all files in the archive folder that are > 7 days old
Get-ChildItem $destination -Recurse |
Where-Object {-not $_.PSIsContainer -and $rightNow.Subtract($_.CreationTime).Days -gt $old } |

# rename all csv files in the Log folder by appending currentDate_currentTime
Get-ChildItem -Path $source\* -Include *.csv  | % {
    $name = $_.Name.Split(".")[0] + "_" + ($_.CreationTime | Get-Date -Format yyyyMMdd) + "_" + ($_.CreationTime | Get-Date  -Format hhmmss) + ".csv"
    Rename-Item $_ -NewName $name
    Move-Item "$($_.Directory)\$name" -Destination $destination

Open in new window

Also remember, this is meant to be a startup script so it should run unattended with no user interaction.
LVL 11
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


You will be best placed to find out. You do this by having proper error handling and logging. The way you have written your script means that even if Move-Item throws an error, everything has gone through fine except the move. You need to handle the potential for an error.

    Move-Item "$($_.Directory)\$name" -Destination $destination -ErrorAction Stop
    "Do something before the file move failed, like maybe send an email, write to a log file, write to SQL, and so on."

Open in new window

Basically your script is predicated on the belief that everything will run smoothly. Error handling is a good thing to learn.
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Note that you are not using the current date for renaming, just for deleting old files in the archive folder. The creation time of each file determines the date appended to the file name.

For renaming you are splitting at the first dot, but only use the first fragment. So if you have files   a.b.csv    and   a.c.csv, created at the same time, both will result in a_yyMMdd_hhmmss.csv.  The rename will happen fine, but the move fail.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
One other thing to be aware of, since you are using the "hhmmss" format string (with lowercase "h"), you could run into duplicates between AM and PM.
ecarboneAuthor Commented:
Qlemo, good catch. I was so wrapped up in looking at the result that I didn't even realize I wasn't using that variable. This is what I get for trying to quickly piece code snippets together. Thanks for the catch. And thanks everyone for the helpful comments and tips.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.