Move file if certain characters in file name match

Solution 1:

If I understand correctly, then this should work for you:

$WorkDir = "C:\1_PDF\source\"
$ESDir   = "C:\1_PDF\ES\"

# get an array of the last four digits from the pdf files in $WorkDir
$LastFour = (Get-ChildItem -Path $WorkDir -Filter '*.pdf' -File | 
    Where-Object { $_.BaseName -match '\d{4}$' } | 
    Select-Object @{Name = 'LastFour'; Expression = { $_.BaseName -replace '.*(\d{4})$', '$1' }}).LastFour

# now do the same for files in $ESDir and see if their last four digits can be found in the $LastFour array
Get-ChildItem -Path $ESDir -Filter 'e00*.pdf' -File | 
    Where-Object { $LastFour -contains ($_.BaseName -replace '.*(\d{4})$', '$1') } |
    Move-Item -Destination $WorkDir -Force

Regex details:

.              Match any single character that is not a line break character
   *           Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(              Match the regular expression below and capture its match into backreference number 1
   \d          Match a single digit 0..9
      {4}      Exactly 4 times
)
$              Assert position at the end of the string (or before the line break at the end of the string, if any)