【问题标题】:Move pdf files matching a substring in powershell在powershell中移动与子字符串匹配的pdf文件
【发布时间】:2021-05-22 04:12:54
【问题描述】:

我需要根据从 location3 的文本文件名中提取的子字符串(在最后一个和倒数第二个 '.' 之间)将 pdf 文件从 location1 移动到 location2。我无法在运行时重命名 location1 的 pdf 文件,因为它有数十万个 pdf 文件,我只需要匹配子字符串模式的几个。

位置 3:

A_b_c_d_e_f_1.2.3.4.5.txt
G_h_i_j_k_6.7.8.9.txt
l_m_n_o_p_2.7.8.4.txt

位置 1:

5_rha_thye_lej.pdf
9_tyoe_hslel_hlssls.pdf
4_shl_heoe_keie_ekye.pdf

我实现了从 txt 文件名中获取子字符串,但是移动匹配模式的 pdf 导致了问题。

$files = Get-ChildItem "location3" -Filter *.txt
forEach ($n in $files) {
$substring = $n.Name.split(".")[-2]
write-host $substring }

Move-Item (Join-Path location1\$substring) -Destination location2

【问题讨论】:

    标签: powershell pdf split substring


    【解决方案1】:

    我不得不多次阅读这个问题,我希望我明白你想要什么:

    • location3 中有 .txt 文件,其文件名以数字结尾,就在扩展名之前,在 . 之后
    • location1 中查找文件名以任何这些数字开头并后跟下划线的 pdf 文件
    • 将这些文件移动到 location2

    如果正确,你可以这样做:

    $location1 = 'D:\Test\sourcefiles'  # the source folder where the .pdf files are
    $location2 = 'D:\Test\destination'  # the destination to move the .pdf files to
    $location3 = 'D:\Test'              # where the .txt files are
    
    # first test if the destinationfolder $location2 exists. If not create it
    if (!(Test-Path -Path $location2 -PathType Container)) {
        $null = New-Item -Path $location2 -ItemType Directory
    }
    
    # get an array of numbers taken from the textfile names in location3
    $numbers = Get-ChildItem -Path $location3 -Filter '*.txt' -File | 
               Where-Object {$_.BaseName -match '\.(\d+)$'} | ForEach-Object { $matches[1] }
    
    # next, loop through the sourcefolder $location1
    Get-ChildItem -Path $location1 -Filter '*_*.pdf' -File |           # find .pdf files that contain an underscore in the name
        Where-Object { $numbers -contains ($_.Name -split '_')[0] } |  # that have a name starting with one of the numbers we got above, followed by an underscore
        Move-Item -Destination $location2
    

    【讨论】:

    • 谢谢@Theo。它解决了移动pdf文件的问题。
    猜你喜欢
    • 2018-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 2014-07-12
    • 2020-12-04
    相关资源
    最近更新 更多