0

I'm new in powershell, I have to execute the following statement recursively:

Get-ChildItem | ForEach-Object {Rename-Item $_ -NewName ("new_filename{0}.smali" -f $nr++)}

In other words I have to rename all the .smali files in the subdirectories with any other name different from the current one (keeping the .smali extension).

1

3 Answers 3

0

Get-ChildItem -Path FolderPath -Filter *.smali -Recurse | ForEach-Object{$_ | Rename-Item -NewName ($.BaseName + StringToAdd + $.Extension) -WhatIf}

Copy the above line as is... Replace the values for FolderPath and StringToAdd and give it a try. If everything looks fine then execute it by removing the -Whatif switch.

3
  • with these changes it run Get-ChildItem -Filter *.sm ali -Recurse | ForEach-Object{$_ | Rename-Item -NewName ($_.BaseNa me + 'a' + $_.Extension)} however I want to completely remove the old file name, so i prefer this: Get-ChildItem -Filter *.sm ali -Recurse | ForEach-Object{$_ | Rename-Item -NewName ( "new_fil ename{0}.smali" -f $nr++) } Aug 12, 2018 at 11:37
  • While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
    – Clijsters
    Aug 12, 2018 at 17:19
  • since I do not want to keep the old file name I used the block "new_fil ename{0}.smali" -f $nr++ which allows you to create several files with the name "fiename" + an incremental number Aug 12, 2018 at 23:44
0

dir is an alias for Get-ChildItem which has a -Recursive parameter.

0
$nr = 0;    Get-ChildItem -Recurse -Filter "*.smali" | Rename-Item -NewName "new_filename$($nr++).smali"

Things to note:

DIR is an alias for Get-ChildItem. Get-ChildItem is more Powershell-y

Your command only looked at the top level directory, so I added the -recurse

Your command would rename all files, not just the "*.smali", so I added the filter.

2
  • with this code I get the following error: Rename-Item : The argument can not be associated with the 'Path' parameter because it is null.. In raw:1 char:56 + Get-ChildItem -Recurse -Filter "*.smali" | Rename-Item $_ -NewName (" ... + ~~ + CategoryInfo : InvalidData: (:) [Rename-Item], Pa rameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNu llNotAllowed,Microsoft.PowerShell.Commands.RenameItemCommand Aug 11, 2018 at 20:50
  • Updated the command to initialize your counter as a first statement, then changed the format string for the new name a bit.
    – kpogue
    Aug 11, 2018 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.