【问题标题】:How to move a file, with the filename based on the folder name, to a subfolder in the same folder如何将文件名基于文件夹名称的文件移动到同一文件夹中的子文件夹
【发布时间】:2023-03-17 12:45:01
【问题描述】:

我已经苦苦挣扎了一段时间,希望有人能帮助我。

我有一堆 *.pdf 文件,其中文件名还包含文件应该移动到的文件夹的名称。 我找到的代码运行良好:

$Folder = "C:\Users\Bob\Desktop\Scripting\Bronmap"
$FileType = "*.pdf"
$Files = Get-ChildItem -Path $Folder -Filter $FileType

$RE = [regex]((Get-ChildItem -Path $Folder -Directory -Name) -Join '|')
ForEach($file in $Files){
    if ($file.BaseName -Match $RE){
        $file | Move-Item -Destination (Join-Path $Folder  $Matches[0] )
    } 
    else {
        $file | Move-Item -Destination (Join-Path $Folder "No_Folder")
    }
} 

我想要的是,将文件移动到命名文件夹中的子文件夹,并具有特定名称“合同”。例如:

$file | Move-Item -Destination (Join-Path $Folder  $Matches[0] "Contracts" )

虽然子文件夹存在,但我无法让它工作。 非常感谢任何帮助。

【问题讨论】:

    标签: powershell path filenames move


    【解决方案1】:

    Join-Path 有两个参数,$Folders$Matches[0] 在你的情况下,所以 "Contracts" 不应该在那里。

    您可以使用两次Join-Path

    (Join-Path (Join-Path $Folder $Matches[0]) "Contracts")
    

    或手动连接合约:

    (Join-Path $Folder ($Matches[0] + "\Contracts"))
    

    【讨论】:

    • 做得很好。请注意,在 PowerShell (Core) 7+ 中,您现在可以将不限数量的路径组件传递给Join-Path;例如Join-Path a b c 在 Windows 上产生 a\b\c
    • 非常感谢 endo64。 -Destination (Join-Path (Join-Path $Folder $Matches[0]) "Contracten") 工作完美
    • 是否可以将文件移动到包含与文件基本名称相同名称的文件夹中?该脚本现在确定一个文件夹名称,在文件中查找该名称,然后将文件移动到相应的文件夹。但我只想使用文件夹名称的最后 8 个字符。
    猜你喜欢
    • 1970-01-01
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 2020-08-30
    相关资源
    最近更新 更多