title: PowerShell ForEach $file in $Files
body: <p>I have a PowerShell script that gets a file listing and moves the files that meet a specific criteria. Why does the <code>foreach</code> loop run even if the object is empty?</p>
  
  <p>I would assume if $i did not exist it would not run. But if there are no results in $filePath why does the forEach loop run once? I have worked around my issue, but I am curious and I tried searching, but I could not find the answer.</p>
  
  <p>To get this to work I just check to make sure $filePath exists before the forEach loop.</p>
  
  <p>For example, if ($filePath){...</p>
  
  <pre><code> $filePath = Get-ChildItem -Path $sourceDir | Where-Object {! $_.PSIsContainer -AND ($_.Name -Match "^XXX_XXX*" -OR $_.Name -Match "^YYY_XX*")}
  
   ForEach($i in $filePath){
       $sfName =  $i.Name
       $sfDir = $i.Directory
       $tFileName = testFile $destDir $sfName
       $sFile = $sourceDir + $sfName
       $tFile = $destDir + $tFileName
  
       moveFile $sFile $tFile
  </code></pre>