Link to home
Start Free TrialLog in
Avatar of kibatsu
kibatsuFlag for Australia

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?

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'
Avatar of Norie
Norie

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?
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

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
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...

$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()
Avatar of kibatsu

ASKER

This worked perfectly thanks!