Reputation: 21
I have a question about the replacement of dots on multiple files, i have the next code:
Dir | Rename-item -NewName{ $_.basename.replace(".","-") + $_.extension }
This code works, but i have folders with dots and the problem is when i run the code, the folders repeat the words after the point like a "file extension":
like this:
How can i resolve this problem, i need just replace the dot on folder name with another word or space or everything i like and the files on the folder just replace before the extension.
thanks!
Upvotes: 2
Views: 817
Reputation: 437638
Unfortunately, the .BaseName
ETS (Extended Type System) property that PowerShell adds to System.IO.DirectoryInfo
instances, i.e. directories, by - unfortunate - design, unconditionally reports the directory name as-is (see GitHub issue #21553 for a discussion; unfortunately, the behavior was declared to be by design).
It is only for System.IO.FileInfo
instances, i.e. files, that .BaseName
strips the extension, i.e., the last .
-separated component.[1]
You can work around the problem by calling the System.IO.Path.GetFileNameWithoutExtension
.NET method, which does not make this distinction (similarly, the type-native .Extension
property doesn't make this distinction either, so it can be used as-is).
Get-ChildItem | Rename-Item -NewName {
[IO.Path]::GetFileNameWithoutExtension($_.Name).Replace('.', '-') + $_.Extension
}
[1] You can verify this as follows:
(Get-TypeData System.IO.DirectoryInfo).Members.BaseName
vs.
(Get-TypeData System.IO.FileInfo).Members.BaseName
Upvotes: 3