title: Matching strings in PowerShell
body: <p>The <strong>gist of this question</strong> is:</p>
  
  <p>So it seems that <code>if ($C -match $b.Name)</code> considers a <em>partial</em> match of a string a match? Is there a better way to force a <em>complete</em> [match] of a string?</p>
  
  <p>I've got a directory that gets populated with a ton of .7z files. I need to clean this directory constantly. There is another script, that predates my employment here, that's currently working, but it's made up of 3000 lines and generates incorrect matches constantly and doesn't log what moved or what was deleted. Part of what makes it so big is that it has a ton of paths for where these files need to be moved to hard coded in it. Occasionally, these paths change and it's a pain in the butt to update.</p>
  
  <p>So I've started making a much smaller script that has all these paths referenced in a CSV file. In addition to these paths, the CSV file also has known filenames recorded in it.</p>
  
  <p>I'm trying to match the file names against the recorded names in my CSV file. It generally works, but sometimes I get incorrect matches.</p>
  
  <p>Let's say I have two files that start similarly, Apple and Apple_Pie. Apple will match to Apple and move to the right directory, but Apple_Pie will first match to Apple and move to the wrong directory. Before the <code>$C</code> variable is cleared out it will match Apple_Pie to the right directory, but by that point Apple_Pie no longer exists in the original directory it needs to be moved from.</p>
  
  <p>So it seems that <code>if ($C -match $b.Name)</code> considers a partial match of a string a match? Is there a better way to force a complete of a string?</p>
  
  <p>I assume that I'm a bit off with my expectations of how <code>-match</code>should work.</p>
  
  <p>The regex stuff I have here is to strip each file name of the date-time that gets added to the file name by another automated process. I use this to isolate the file name I want to match.</p>
  
  <pre><code>$Wild = "C:\Some\Folder\With\Files\"
  
  $CSV = "C:\Another\Folder\Paths.csv"
  
  $Content = gci $wild
  
  $Reg1 = [regex] '_[0-9]{4}-[0-9]{2}-[0-9]{2}[A-Z]{1}[0-9]{2}_[0-9]{2}_[0-9]{2}'
  
  $Reg2 = [regex] '[0-9]{4}-[0-9]{2}-[0-9]{2}[A-Z]{1}[0-9]{2}_[0-9]{2}_[0-9]{2}'
  
  $Paths = import-csv -path $CSV -header Name, Path
  
  foreach ($a in $content) {
      $c = $a.BaseName
  
      if ($c -match $reg1) {
          $c = $c -replace $regyear
      }
      elseif ($c -match $reg2) {
          $c = $c -replace $reg2
      }
  
      foreach ($b in $Paths) {
  
          if ($c -match $b.Name) {
              Do something
          }
      }
  }
  </code></pre>