I don’t do much scripting and wanted to know what I could do to make the script I came up with more elegant in powershell. TBH, I’m a little baffled why powershell is keeping a space unless I select a non-spaced space.
Explanation:
I had a flat directory with file names which included where these files came from. Let’s say the origins are listed as X1, X2, … I decided to place all these files into their respective directories. For example, “X1 Title.pdf” → directory entitled “X1” with the file still named “X1 Title.pdf”.
I wanted to remove the "X1 " (including the blank space) from the file name using powershell.
The following command works:
get-childitem -recurse -file -filter *pdf | Rename-Item -NewName { $.Name -replace $.Directory.Name + “”, “” }
BUT:
- get-childitem -recurse -file -filter *pdf | Rename-Item -NewName { $.Name -replace $.Directory.Name + " ", “” }
(adding to search for a blank space after the directory name)
Seemingly this is expecting 2 spaces after the X1 (directory name) and thus does not rename anything.
- get-childitem -recurse -file -filter *pdf | Rename-Item -NewName { $.Name -replace $.Directory.Name, “” }
Here I removed the + " " (or just use the + without any quotes afterwards), and the result is to have a blank space as the first character in the file name.
So I’m a little confused. If I specify a blank space, it expects 2 blank spaces. If I don’t specify a space after the directory name, it retains the blank space.
The only thing that works is to add a non-spaced space (i.e., “”) after the directory name.
As I wrote above, I figured out what code works for what I want, but if someone would be kind enough to either explain to me why I need the ’ + “” ’ or to provide a more elegant way to indicate the search to also include blank spaces, I’d appreciate it.
thanks!