title: Move Folders and files from folders/subfolders with same name (copies to be renamed)
body: <p>(I have tried to rewrite this to be more clear)</p>
  
  <p>I have a problem with having hundreds of folders and files (each start with ABC and then numbers 001-936) that need to be moved to a single folder with the same name. For example:</p>
  
  <pre><code>C:\folders\ABC001 
  C:\folders\random\ABC001\ 
  C:\folders\files\ABC001.pdf 
  C:\folders\ABC002.pdf 
  C:\folders\ABC002\  
  C:\folders\needs sorting\ABC002\
  </code></pre>
  
  <p>That I would like to move all files and folders to a folder with the same name:</p>
  
  <pre><code>C:\folders\ABC\ABC001\ 
  C:\folders\ABC\ABC002\  
  and so on...
  </code></pre>
  
  <p>However, sometimes the orginal folder and/or file will have a duplicate in the destination folder(or may already have since folders already exist), so I want it to add to the name (1), (2), etc.</p>
  
  <pre><code>C:\folders\ABC\ABC001\ABC001\
  C:\folders\ABC\ABC001\ABC001 (1)\ 
  C:\folders\ABC\ABC001\ABC001.pdf 
  C:\folders\ABC\ABC002\ABC002.pdf 
  C:\folders\ABC\ABC002\ABC002\  
  C:\folders\ABC\ABC002\ABC002 (1)\
  </code></pre>
  
  <p>Any help would be greatly appreciated, I have been trying to solve this for weeks (everytime I needed the files) but am new to scripting/code. I started with:</p>
  
  <pre><code>for /R "C:\folders" %x in (*abc123*.*) do move "%x" "D:\folders\abc\abc123"
  </code></pre>
  
  <p>Closest attempt (minor edits to another code):</p>
  
  <pre><code>function MoveFileToFolder ([string]$source,[string]$destination){
  # get a list of source files
  $files = Get-ChildItem -Path $source -Recurse | ?{($_.PSIsContainer)}
  # verify if the list of source files is empty
  if ($files -ne $null) {
      foreach ($file in $files) {
      $filename = $file.Name
      $filebase = $file.BaseName
      $fileext = $file.Extension
  # verify if destination file exists
      $filenameNU = $filename 
      if (Test-Path (Join-Path $destination $filename)) {
          $n = 0
          while ((Test-Path (Join-Path $destination $filenameNU)) -eq $true)
          {
          $filenameNU = $filebase + "(" + ++$n + ")" + $fileext
          }
      }
      Move-Item $file.FullName (Join-Path $destination $filenameNU)
      }
  }
  }
  
  MoveFileToFolder C:\folders\ C:\folders\abc\abc123
  </code></pre>
  
  <p>(I would try and run this in Powershell for each subfolder, but it became very hard to keep up with)</p>
  
  <p>Thank you for reading.</p>