kibatsu
asked on
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?
New file name: 'filename 071217 .ext'
I'd expect the file to be renamed something like: 'filename12345 071217.ext'
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)"
}
Original file name: 'filename12345.ext'New file name: 'filename 071217 .ext'
I'd expect the file to be renamed something like: 'filename12345 071217.ext'
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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?
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...
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()
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)))
}
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()
ASKER
This worked perfectly thanks!
Is there anything unusual about the names of the files you are moving?