0

I'm trying to find two files called:

bitbucket_20181013.bak
bitbucket_20181013-237823-23.tar

I'm trying to find these files using the date extension "20181013" and I want to rename it to "{todaysDate}_bitbucket_backup.{ext}"

So far I have the following:

$date = [DateTime]::Nw.ToString("yyyyMMdd")
$file = "*$date*"
$name = "$($date)_Bitbucket_Backup"

Get-ChildItem -Path Microsoft.PowerShell.Core\FileSystem::\\KERGRINFS4\Seagate\Bitbucket_Backups\backups |
    Where-Object { $_.Name -like $file } |
    %{ Rename-Item -LiteralPath $_.FullName -NewName "$name + $_.extension" }

But it doesn't work, it returns: "20181014_Bitbucket_Backup + bitbucket_20181014.bak.extension" instead of "20181014_Bitbucket_Backup.bak"

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328

3 Answers3

0

Change $_.extension to $($_.extension).

"$_.extension"    # Give me string that is $_, then add the literal string .extension to it
"$($_.extension)" # evaluate the expression $_.extension, then give me the results of that as a string.
G42
  • 9,791
  • 2
  • 19
  • 34
0

I'm not sure I understand you, but if got you right, you want to change files contains the string '20181013' and rename it to todays date using the yyyyMMdd date format?

You can use String.Replace and Rename-Item in one command to make the code more readable as well, try that:

$Path = 'Microsoft.PowerShell.Core\FileSystem::\\KERGRINFS4\Seagate\Bitbucket_Backups\backups'
$OldString = 'bitbucket_20181013'
$NewString = "{0}_Bitbucket_Backup" -f [datetime]::now.tostring("yyyyMMdd") 

Get-ChildItem $Path | ? {$_.Name -match $OldString} | 
% {Rename-Item $_.FullName -NewName ($_.Name.Replace($OldString,$NewString)) 
}
Avshalom
  • 8,657
  • 1
  • 25
  • 43
0

I think you don't really need to embed variables when defining "new name". I'd also suggest to be more consistent with aliases.

ls | where { $_.Name -like $file } | foreach { ren $_.FullName -NewName ($name + $_.extension) }
Mike Twc
  • 2,230
  • 2
  • 14
  • 19