r/PowerShell • u/[deleted] • Jul 05 '21
Question Powershell bugged, cant batch rename files
Can anyone help please? I'm really frustrated.
I need to add certain prefix to name of every file in a directory.
I'm using this: dir | Rename-Item -NewName {"EN " + $_.Name}
This command worked perfectly for about 400 files so far, but today for whatever mysterious reason, the very same command (no typos, I pulled it out from history by pressing UP arrow) errors out saying I cant exceed 260char limit. It keeps naming the files in loop. So for example "video.mp4" is not renamed to "EN video.mp4" but "EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN EN video.mp4"
Any ideas how do I fix it please?
2
u/Technane Jul 05 '21
this sounds like your gettting possibly 12 files, looping them then running the loop again, obvs not testing if the file has already been renamed, so no filter -notmatch "EN V"
or your looping the GET-childitem every time your loop runs, means it rebuilding your list.
-1
Jul 05 '21
Why would that work on certain number of files though? And yesterday it worked on etire batch of 48. Doesn't make much sence, but I'll try to change the code
3
Jul 05 '21
fixed it,
in case anyone runs into same issue.
get-childitem * | rename-item -newname { "EN " + $_.Name }
11
u/PhDinBroScience Jul 05 '21
Get-ChildItem | % { Rename-Item -Path $_ -NewName "EN $_.Name"}
1
u/Binaryoh Jul 06 '21
Could anyone explain why this works?
4
u/PhDinBroScience Jul 06 '21
The objects output by
Get-ChildItemare piped to a (shorthand)ForEach-Objectcmdlet that runsRename-Itemon each object returned byGet-ChildItem.Here's a breakdown:
The
Get-ChildItemcmdlet is run. Instead of a text representation of the returned objects being sent to the console, the objects themselves are passed on as input to the next statement in the pipeline. The objects will be a directory listing of the current working directory.The pipe
|signifies that the output of the prior command should be passed on to the next command in the pipeline.
% { }is the shorthand version ofForEach-Object. I was just being lazy by using it instead of the full name of the cmdlet. For every object that is passed to it from the previous command in the pipeline (Get-ChildItem), it runs whatever command is in the curly braces on that object.The
Rename-Itemcmdlet in theForEach-Objectbraces is what actually does the work of renaming the file. The$_argument to the-Pathparameter represents the current object that was passed on the pipeline by the previous command. In this example, it's going to be one of the directory objects returned by theGet-ChildItemcmdlet. The"EN $_.Name"argument to the-NewNameparameter is a concatenation of the string he wanted as a prefix to the file's name and the.Nameproperty of the$_object currently being worked on.After
Rename-Itemis done for the current object,ForEach-Objectmoves on to the next object and runs theRename-Itemcmdlet for all the remaining objects sequentially.Not sure if I explained that well, but that's what's happening step-by-step.
2
u/Binaryoh Jul 06 '21
Aha, i see now. It was the foreach alias and the "-Path $_" that threw me off here. Did not know "%" was the alias for that. And i did not know the "-Path" argument was required. Thank you for the thorough step by step explanation!
2
u/PhDinBroScience Jul 06 '21
Yeah, some cmdlets will just vacuum up whatever you throw at them on the pipeline and do what you'd expect them to do, but others require you to specify every argument under the sun.
If I'm unsure of its behavior/if it requires specifying arguments instead of just eating the input object, I'll usually tack on a
-WhatIfto the end of the cmdlet and see if it succeeds or throws an error.I only do that if I'm doing something manually in the console or a one-liner or something like that though, in actual scripts I always fully specify arguments and their parameters to be as readable and explicit as possible.
2
u/Zalrog1 Jul 05 '21 edited Jul 05 '21
Maybe try using get-childitem and one of rename-item's optional parameters like -replace.
-5
Jul 05 '21
Ok, this is F* ridiculous!
There is 48 files in the folder. When I use that command to rename them it fails with that stupid loop.
If I split the files to 4 folder, 12 videos per folder, the command works flawlessly on all of them.
Can't powershell handle 48 files or what? It worked yesterday.
2
u/FiredFox Jul 05 '21
Powershell might be experiencing a PEBKAC loop.
0
Jul 08 '21
Yeah, I was hoping someone here could point out what exactly is the problem and how do I fix it, but instead I got bunch of downvotes and comments like yours. Very useful.
Thanks.
1
u/FiredFox Jul 08 '21
No, you came in here acting like you couldn't possibly have done anything wrong and the fault must clearly be with Powershell.
That is why you are getting snarky comments and downvotes.
1
Jul 10 '21
Yes, becasue it doesn't make sence that the code worked fine for several months and suddenly it starts acting strange on the exact same input. I thought there is something cached messing with powershell or idk.
When you write a script, test it, run it every single week from February to July and one day the script suddenly starts spitting bad results everey time you run it, the last thing that comes to your mind is that the script was bad from the start. If it was, why did it work with no errors whatsoever ?
I admit the way I talk wasn't the best choice, but I got super frustrated becasue A) I need it done fast otherwise I can keep smashing F2 and renaming it myself but I have more important things on my schedule than wasting hours on troubleshooting one line of code and B) Fuck powershell and everything involved!
I came here becasue I suck at scripting and assumed people here would know what's wrong, would tell me: "here is your problem you little cunt..." and ultimately would save my time so I can rename the stupid files and get back to work.
I tried to post screenshots and record video (I couldnt post it here because reasons) I tried to provide as much details as possible in case someone here would be willing to help and would want to try to reproduce the issue on their machine.
I'm fine with snarky sarcastic answers, swear, call me stupid dumbf*ck, but try to provide something constructive at the same time. Otherwise I can go to Yahoo answers or Quora.
0
Jul 05 '21
[deleted]
4
u/SeeminglyScience Jul 05 '21
It's called a "delay-bind script block" argument https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_script_blocks?view=powershell-7.1#using-delay-bind-script-blocks-with-parameters
0
Jul 06 '21
[deleted]
2
u/SeeminglyScience Jul 06 '21
It's invoked every pipeline item rather than once at the very start.
0
Jul 06 '21
[deleted]
2
u/SeeminglyScience Jul 06 '21
Yeah pretty much. It's a pretty obscure feature but can be really useful interactively. I wouldn't really recommend it in a script though, I'd prefer to just enumerate.
It does have some limitations, like parameter type must not be scriptblock or object, and the parameter needs to accept pipeline input. But it can be some nice syntactic sugar when it works.
Full disclosure though, I basically never use this because I had some misconceptions about it initially and avoided it for a long time.
2
u/jrobiii Jul 05 '21
Found that the curly braces are used when you pipe results to `Rename-Object`. That is how `$_` becomes relevant. This was new to me as well. I've never thought to pipe to `Rename-Object` instead I use a `Foreach-Object`... which is probably way less efficient.
0
Jul 05 '21
[deleted]
2
u/jrobiii Jul 05 '21
Thanks for the input.
if I was really worried about performance I wouldn't be writing in Powershell.
Sometimes you don't have the option to use another language
0
Jul 05 '21
Rename-Item : Cannot create a file when that file already exists.
At line:1 char:7
+ dir | Rename-Item -NewName ("SV " + $_.Name)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:_ME6886_expo... video 9x16.mp4:String) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
3
u/jrobiii Jul 05 '21
Can you post your code?