0

I am fairly new to Powershell scripting and I have to write a script that copies a file from a certain path and pastes it in a new folder that is created with the current date. This is what I got so far.

New-Item -Path "c:\users\random\desktop\((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory

copy-item c:\users\random\desktop\rand.txt 'c:\users\random\desktop\((Get-Date).ToString('yyyy-MM-dd'))

When I run this script, it creates a directory called ((Get-Date).ToString('yyyy-MM-dd')) instead of today's date.

When this script runs, it has to create a directory with the current date and paste that file in it. So if I were to run it once a day for 5 days, it should create 5 different folders with the file in each of them. Any help is much appreciated.

3 Answers 3

1

If you are looking to keep with those 2 lines of code you need to wrap the Get-Date portion in $(). This tells PS to resolve that code before using the string inside the double quotes. enter image description here

So your code would look like this:

New-Item -Path "c:\users\random\desktop\$((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory
copy-item c:\users\random\desktop\rand.txt "c:\users\random\desktop\$((Get-Date).ToString('yyyy-MM-dd'))"

However, you could have one flaw if your script is ever executed within microseconds of midnight: Each command would get a separate date.

A better method to use is to simply grab the date in a variable and use that in both of your commands. It will also make it more readable:

$cDate = Get-Date -format yyyy-MM-dd
$NewPath = "C:\Users\random\desktop\$cDate"
New-Item -Path $NewPath -ItemType Directory
Copy-Item c:\users\random\desktop\rand.txt $NewPath

This would ensure you get the same date value if you happen to pass midnight when it runs. Although, that is probably not going to be an issue it doesn't hurt to be safe.

Sign up to request clarification or add additional context in comments.

Comments

0

you miss a dollar sign before the bracket

"c:\users\random\desktop**$**((Get-Date).ToString('yyyy-MM-dd'))"

1 Comment

"c:\users\random\desktop$((Get-Date).ToString('yyyy-MM-dd'))"
0

Create a variable to store your GetDate, then convert it in to a string.

$currentdate = date $currentdate2 = $currentdate.ToString("yyyy-MM-dd")

Hence your code folder path will be 'c:\users\random\desktop\$currentdate2'

1 Comment

By the way, shouldn't this be in serverfault?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.