title: Powershell to move Excel files based on Initial part of the file name
body: <p>I have hundreds of excel files like the following in directory called <code>D:\TestARC_Source</code></p>
  
  <pre><code>5020190429.dat
  5120190429.dat
  602019111121.dat
  702019050926.dat 
  etc.
  </code></pre>
  
  <p>I need a script to move them to respective folders based on first two characters of file name. Folders are already created on target directory.</p>
  
  <pre><code>D:\TestARC_Destination\file_50
  D:\TestARC_Destination\file_51
  D:\TestARC_Destination\file_60
  D:\TestARC_Destination\file_70
  </code></pre>
  
  <p>Files should move to respective folders based on first two characters of file name. For example <code>5020190429.dat</code> moves to <code>50_file</code> folder.</p>
  
  <p>I am trying to edit below script but it's not working. I have a very little knowledge in PS script and I'll appreciate if you can help me out.</p>
  
  <pre><code>$SourceFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Source\"
  $targetFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Destination\"
  
  # Find all files matching *.sql in the folder specified
  Get-ChildItem -Path $SourceFolder -Filter *.dat | ForEach-Object {
  
      # Combine the source filename and target directory
      # The source filename has all instances of _ replaced with \
      # Cast the resulting string to a FileInfo object to take advantage of extra methods
      [System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))
  
      # Create the directory if it doesn't already exits
      if (!(Test-Path) $destination.Directory.FullName)
      { 
          New-item -Path $destination.Directory.FullName -ItemType Directory 
      }
  
      # Copy the source to the target directory
      copy-item -Path $_.FullName -Destination $Destination.FullName 
  } 
  </code></pre>