Link to home
Start Free TrialLog in
Avatar of luketr
luketr

asked on

Powershell script to create folder with time stamp.

Hi,

I need to write a powershell script that will create a folder with today’s time stamp and move all the files in the directory to the folder that has just been created with the time stamp.

Thanks

Luke  
Avatar of KenMcF
KenMcF
Flag of United States of America image

To create the folder you can use this

New-Item "C:\temp\$(get-date -f yyyyMMdd)" -type directory

To move the file
$1Day = (get-date).adddays(-1)
((get-date $1day -f yyyyMMdd))

Get-ChildItem c:\temp | %{
    Where {(get-date $_.lastwritetime -f yyyyMMdd) -eq (get-date $1day -f yyyyMMdd)} | 
        Move-Item "C:\temp\$(get-date -f yyyyMMdd)"

}

Open in new window

Avatar of Qlemo
Line 2 above is for debugging only, and can be removed. Besides that, the code is not working that way, the foreach-object (%) is wrong here, but should work if  %{  and the closing } are removed.
For my taste there is too much of get-date above - that might not perform well with a lot of files.
$src = C:\Temp
$target = C:\Temp\(get-date).ToString("yyyyMMdd")
$yesterday = (get-date).adddays(-1).ToString("yyyyMMdd")
gci $src | ? {$_.lastwritetime.ToString("yyyyMMdd") -eq $yesterday} | move-item $target

Open in new window

Avatar of luketr
luketr

ASKER

When i try and run the script i get the following error.


PS C:\Documents and Settings\dipadmin> $src = C:\Temp
The term 'C:\Temp' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try a
gain.
At line:1 char:14
+ $src = C:\Temp <<<<
PS C:\Documents and Settings\dipadmin> $target = C:\Temp\(get-date).ToString("yyyyMMdd")
The term 'C:\Temp\' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try
again.
At line:1 char:19
+ $target = C:\Temp\( <<<< get-date).ToString("yyyyMMdd")
PS C:\Documents and Settings\dipadmin> $yesterday = (get-date).adddays(-1).ToString("yyyyMMdd")
PS C:\Documents and Settings\dipadmin> gci $src | ? {$_.lastwritetime.ToString("yyyyMMdd") -eq $yesterday} | move-item $
target
Sorry, the first line needs to sound:
$src = "C:\Temp"
Avatar of luketr

ASKER

it's erroring on the 2nd line

$target = "C:\Temp\"(get-date).ToString("yyyyMMdd")

The term 'C:\Temp\' is not recognized as a cmdlet, function, operable program, or script file. Verify the term and try
again.
At line:1 char:19
+ $target = C:\Temp\( <<<< get-date).ToString("yyyyMMdd")
ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial