如果文件名中的某些字符匹配,则移动文件

如果文件名中的某些字符匹配,则移动文件

我有一个文件夹,里面有文件($WorkDir):“330526.pdf”、“330527.pdf”、“330528.pdf”等。

然后我有另一个包含文件的文件夹($ESDir):“e00526.pdf”,“e00527.pdf”,“e00528.pdf”等。

现在我想搜索中的文件$WorkDir,也想搜索中的文件$ESDir

然后,如果文件名中的最后 4 个字符/数字匹配(“xx0526"),我想将匹配的文件从“ $ESDir”移动到$WorkDir

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

答案1

如果我理解正确的话,那么这应该对你有用:

$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

正则表达式详细信息:

.              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)

相关内容