0

I have two folders all with multiple .msg files I need to add a numerical, sequential prefix to. One folder has over 1500 individual files.

I want the end result to go from this:

"[EXTERNAL] RE%3A Auth....msg"
"Fees....msg"
"Hello There...msg"

To this:

"1[EXTERNAL] RE%3A Auth....msg"
"2Fees....msg"
"3Hello There...msg"

I have tried to combine a few results from other similar threads I have found here and have come up with the following:

$i = 1
@Get-ChildItem *.msg | %{Rename-Item $_ -NewName ("{0:000#}_$($_.directory.name).msg" -f $i++)}

When I run this script, I get the following errors:

At C:\users\me\Documents\PrependNumbers.ps1:10 char:5
+ @Get-ChildItem *.msg | %{Rename-Item $_ -NewName ("{0:000#}_$($_.dire ...
+     ~~~~~~~~~~
Unexpected token '-ChildItem' in expression or statement.
At C:\users\me\Documents\PrependNumbers.ps1:10 char:16
+ @Get-ChildItem *.msg | %{Rename-Item $_ -NewName ("{0:000#}_$($_.dire ...
+                ~~~~~
Unexpected token '*.msg' in expression or statement.
At C:\users\me\Documents\PrependNumbers.ps1:10 char:1
+ @Get-ChildItem *.msg | %{Rename-Item $_ -NewName ("{0:000#}_$($_.dire ...
+ ~~~~
The splatting operator '@' cannot be used to reference variables in an expression. '@Get' can be used only as an
argument to a command. To reference variables in an expression use '$Get'.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

I feel like I probably just have a syntax error somewhere, but am unable to tell where exactly from these errors.

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 2
    In the last error, it tells you the issue with your syntax. You have a random `@` as if you were splatting. – Abraham Zinala Jul 26 '22 at 20:34
  • Syntax error aside: A more efficient way to rename is to pipe directly to `Rename-Item` and formulate the new name in a _delay-bind script block_ - see [this answer](https://stackoverflow.com/a/53393980/45375). – mklement0 Jul 26 '22 at 20:42
  • `Rename-Item` receives a list of files, so no need for `| %{Rename-Item`, just `| Rename-Item` is enough – phuclv Jul 27 '22 at 03:13

0 Answers0