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
Get-Item
instead ofGet-ChildItem
and append\*
to the input path to make-Include
work as intended.See this answer for background information.
Use the
.BaseName
and.Extension
properties in the delay-bind script block you're passing toRename-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.