Search code examples
windowspowershellrenamemicrosoft-file-explorer

PowerShell - Rename Files based on a matching .basename


I am looking to rename a .wav file when the corresponding .txt file is renamed

The Files have the same basename but are different file types.

I am using get-content on the .txt file to get the name I would like to use.

But cant seems to get the .wav files linked with the matching .txt files.

Any help would be much appreciated on this

this code is what I am using to update the .txt files at once individually using their data. Not sure how I can add the .wav feature within this.

$txtFiles = Get-ChildItem c:\test\*.txt
>> foreach ($File in $txtFiles) {
>>     $File.fullname
>>     $Data = (get-content $File.fullname)[6,7,4]-Join 1
>> $Data = $Data -Replace ":",","
>>     $Rename = (Rename-item $file -NewName $file$data)
>>
>> }

I was thinking maybe something like this would be on the nose of what I need, but not 100% sure

Get-ChildItem "C:\test" -recurse | where {$_.fullname.wav -like $_.fullname.txt} | Select name

Solution

  • Use Group-Object to group your *.txt and *.wav files by shared base name (file name without extension):

    Get-ChildItem c:\test\*.txt, c:\test\*.wave | 
      Group-Object BaseName |
      ForEach-Object {
        $pairedFiles = $_.Group
        $data = (Get-Content $pairedFiles[0].FullName)[6,7,4] -join 1 -replace ':', ','
        $pairedFiles |
          Rename-Item -NewName { $_.BaseName + $data + $_.Extension } -WhatIf
      }
    

    Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf and re-execute once you're sure the operation will do what you want.