Yaffai313
Yaffai313

Reputation: 1

Powershell Script to copy file to new folder

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.

Upvotes: 0

Views: 2170

Answers (3)

user847990
user847990

Reputation:

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.

Upvotes: 1

Ponilz
Ponilz

Reputation: 119

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'

Upvotes: 0

CaMeL
CaMeL

Reputation: 26

you miss a dollar sign before the bracket

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

Upvotes: 0

Related Questions