When using powershell to rename files with their directory name and file name, my code works, except in the first file in a directory, it gives it two copies of the directory name. So the file book1.xlsx
in folder folder1
should become folder1book1.xlsx
but it becomes folder1folder1book1.xlsx
. The remaining files in folder1
are correctly named folder1book2.xlsx
, folder1book3.xlsx
, etc.
I have a directory, with many sub-directories. In each sub-dir are files that need their sub-dir name added in.
I've been following this code. For me it looks like:
dir -Filter *.xlsx -Recurse | Rename-Item -NewName {$_.Directory.Name + "_" + $_.Name}
I've also tried
--setting the Recurse -Depth 1
so that it doesn't keep looking for folders in the sub-folders.
--using ForEach-Object {$_ | ...
after the pipe, similar to this.
--running it in Visual Studio Code rather than directly in PowerShell, which turns it into:
Get-ChildItem "C:\my\dir\here" -Filter *.xls -Recurse | Rename-Item -NewName {$_.DirectoryName + '_' + $_.Name}
--putting an empty folder inside the sub-directory, setting -Depth 2
to see if that will "catch" the recurse loop
I would expect the files to be named folder1_book1.xlsx
, folder1_book2.xlsx
, folder1_book3.xlsx
.
But all of the attempted changes above give the same result. The first file is named folder1_folder1_book1.xlsx
[INCORRECT], folder1_book2.xlsx
[CORRECT], folder1_book3.xlsx
[CORRECT].
A workaround might be writing an if
statement for "not files that contain the sub-directory name" as suggested here. But the link searches for a text string not an object (probably not the correct term) like @_.Directory.Name
. This post shows how to concatenate objects but not something like @_.Directory.Name
. Having to put in an if statement seems like an unnecessary step if -Recurse
worked the way it should, so I'm not sure this workaround gets at the heart of the issue.
I'm running windows 10 with bootcamp on a 2018 iMac (I'm in Windows a lot because I use ArcMap). Powershell 5.1.17134.858. Visual Studio Code 1.38.0. This is a task I would like to learn how to use more in the future, so explanations will help. I'm new to using PowerShell. Thanks in advance!