Home > Net >  Adding _ at the end of every file name of 3 type of extension in a folder
Adding _ at the end of every file name of 3 type of extension in a folder

Time:08-29

How could I modify name of every file by adding _ before the filename extension in a Get-ChildItem -Include without calling 3 times a Foreach.

My script works, but I would like to simplify it by using -Include and not -Filter.

function renommer_fichier {

    $files = Get-ChildItem -Path C:\mestp\mesFichiers -Filter *.jpg
        Foreach ($file in $files)
        {
            $file | Rename-Item -NewName { $_.Name -replace '.jpg', '_.jpg' }
        }
    $files = Get-ChildItem -Path C:\mestp\mesFichiers -Filter *.mp3
        Foreach ($file in $files)
        {
            $file | Rename-Item -NewName { $_.Name -replace '.mp3', '_.mp3' }
        }
    $files = Get-ChildItem -Path C:\mestp\mesFichiers -Filter *.mpeg
        Foreach ($file in $files)
        {
            $file | Rename-Item -NewName { $_.Name -replace '.mpeg', '_.mpeg' }
        }

}

CodePudding user response:

  • Unfortunately, the -Include parameter - which supports specifying multiple patterns - doesn't work as one would intuitively expect:

  • Use the .BaseName and .Extension properties in the delay-bind script block you're passing to Rename-Item to facilitate inserting _ before the filename extension.

Get-Item -Path C:\mestp\mesFichiers\* -Include *.jpg, *mp3, *.mpeg |
  Rename-Item -WhatIf -NewName { $_.BaseName   '_'   $_.Extension } 

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

  • Related