Home > Back-end >  Powershell – Insert a Number Before folder Name – Increment
Powershell – Insert a Number Before folder Name – Increment

Time:01-17

I'm trying to Insert a Number Before folder Name – Increment using Powershell.

The path below is where the subfolders reside.

C:\Users\Chris Hewitt\Documents\Project\Action Log & Project Stuff\2022

I found the code below online and tried to get it to work with no luck. I'd really appreciate it if someone could provide feedback as to why this is not working. Thanks in advance


Code:

$BasePath = "C:\Users\Chris Hewitt\Documents\Project\Action Log & Project Stuff\2022"
$Index = 0
$Folds = Get-ChildItem -Path $BasePath -Attributes "D"

ForEach ($Folder in $Folds) {
  
  $Index  = 1
  Rename-Item -Path "$($Folder.fullname)" -NewName "$Index.$Folder"

}

"$Index folders were processed."

CodePudding user response:

Issue is that $($Folder.fullname) returns a full filepath which is invalid to rename something to. You need to hit the .name Attribute. For example

ForEach ($Folder in $Folds) {

   $Index  = 1
   Rename-Item -Path "$($Folder.FullName)" -NewName "$Index.$($folder.name)"
  
 }
$VerbosePreference = "Continue"
Write-Verbose "$index folders were processed"
  • Related