Powershell code to move and rename files

I have a powershell script that does a number of things, and part of it is to check a path for files, then shift them to an archive location and append the date to the file name. It works fairly well, except it seems to drop part of the original filename when appending the date.
Any ideas?

Get-ChildItem -Path D:\File\Path\*.* | ForEach-Object {
    Move-Item -Path $_.FullName -Destination "D:\File\Path\Archive\$($_.BaseName,(Get-Date).ToString("MMddyy"),$_.Extension)"
}

Open in new window

Original file name: 'filename12345.ext'
New file name: 'filename 071217 .ext'


I'd expect the file to be renamed something like: 'filename12345 071217.ext'
LVL 2
kibatsuAsked:
Who is Participating?
 
oBdAConnect With a Mentor Commented:
Can't reproduce the dropping, but your syntax is off, anyway. You're creating an array inside the subexpression, which is then joined by space.
And to rename files, a date format of yyMMdd or yyyyMMdd is better suited, because it'll sort by date.
Then you can put the Ge-Date outside the loop; no need to call a cmdlet each iteration.
$DateString = Get-Date -Format 'yyMMdd'
Get-ChildItem -Path D:\File\Path\*.* | ForEach-Object {
	Move-Item -Path $_.FullName -Destination "D:\File\Path\Archive\$($_.BaseName)_$($DateString)$($_.Extension)"
}

Open in new window

1
 
NorieVBA ExpertCommented:
That works fine for me, the original filenames are kept and the current date is added.

Is there anything unusual about the names of the files you are moving?
0
 
Lasse BodilsenSystem AdministratorCommented:
my guess would be that the part being dropped is not part of $_.BaseName,  can you check for that by making it output .BaseName to a logfile?
0
 
Jose Gabriel Ortega CCEO J0rt3g4 Consulting ServicesCommented:
I think is something related to the Get ChildItem doesn't behave like the FileInfo that it should,
I make the treat with the actual FileInfo...

$tpath="D:\File\Path"
Get-ChildItem -Path "$tpath\*.*" | ForEach-Object {
    $fi = New-Object System.IO.FileInfo -ArgumentList $_.FullName
    #$TAIL =  -join $($fi.BaseName ,(Get-Date).ToString("MMddyy"),$fi.Extension)
    #Move-Item -Path $fi.FullName -Destination "$tpath\Archive\$TAIL"
    Move-Item -Path $fi.FullName -Destination ("$tpath\Archive\" + (-join $($fi.BaseName ,(Get-Date).ToString("MMddyy"),$fi.Extension)))
}

Open in new window


The 2 lines in the comment are just the steps I followed to get to the actual last line. from the Destination with $( var1,var2) you're getting an array so you just need to convert it to plain using -join and .tostring()
0
 
kibatsuAuthor Commented:
This worked perfectly thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.