如果文件在 Powershell 等中匹配,则将文件移动到子文件夹?

Move files to subfolders if they match in Powershell etc?

我已经在谷歌上搜索了一段时间,但找不到任何解决方案。

所以我在一个文件夹中有一堆文件,在这个文件夹中我有子文件夹。

如果这些文件与其中任何一个匹配,我想将它们移动到子文件夹中。

像这样:

示例 - 文件:

示例 - 目录:

目标:

可行吗?

顺便说一句,可能不止一个子文件夹与文件名匹配。如果是这样,文件移动到哪个子文件夹都没有关系。

这是完成这项工作的一种方法... [grin]错误检查或处理几乎为零,因此您可能需要添加它。也没有任何关于 done/not-done.

的记录

它的作用...

  • 设置常量
    所有这些。 [咧嘴一笑]
  • 创建要使用的文件和目录
    当您准备好使用自己的数据时,删除整个 #region/#endregion 块。
  • 获取目标位置的目录列表
  • 创建这些目录名称的正则表达式 OR
  • 获取目标目录中的文件列表
  • 遍历这些文件
  • 测试每个文件的 .BaseName 属性 与之前
  • 的目录名称正则表达式的匹配
  • 如果是,创建一个完整的目录名并移动文件
  • 如果否,将警告写入警告流
    默认情况下是打开的,所以当找到这样的文件时你必须看到它。
  • 完成遍历文件列表

代码...

$SourceDir = "$env:TEMP\user3764769"

#region >>> create some files & dirs to work with
#    when ready to do this for real, remove this entire block
if (-not (Test-Path -LiteralPath $SourceDir))
    {
    # the $Null suppresses unwanted "what was done" output
    $Null = New-Item -Path $SourceDir -ItemType 'Directory' -ErrorAction 'SilentlyContinue'
    }
@'
Propulsion_mal_2020.jpg
Axevalla Vivid Wise As Goop.jpg
Dagens stjarna Cyber Lane.jpg
640px Elian Web heat.jpg
'@ -split [System.Environment]::NewLine |
    ForEach-Object {
        $Null = New-Item -Path $SourceDir -Name $_ -ItemType 'File' -ErrorAction 'SilentlyContinue'
        }
@'
Propulsion
Vivid Wise As
Cyber Lane
Vitruvio
'@ -split [System.Environment]::NewLine |
    ForEach-Object {
        $Null = New-Item -Path $SourceDir -Name $_ -ItemType 'Directory' -ErrorAction 'SilentlyContinue'
        }
#endregion >>> create some files & dirs to work with

$DirList = Get-ChildItem -LiteralPath $SourceDir -Directory
# the "|" is what regex uses for `-or`
$RegexDL = $DirList.Name -join '|'

$FileList = Get-ChildItem -LiteralPath $SourceDir -File

foreach ($FL_Item in $FileList)
    {
    # the matched value is stored in $Matches[0]
    if ($FL_Item.BaseName -match $RegexDL)
        {
        $DirName = $Matches[0]
        $FullDirName = Join-Path -Path $SourceDir -ChildPath $DirName

        Move-Item -LiteralPath $FL_Item.FullName -Destination $FullDirName
        }
        else
        {
        Write-Warning ''
        Write-Warning (    'No matching directory was found for [ {0} ].' -f $FL_Item.Name)
        Write-Warning '    The file was not moved.'
        }
    } # end >>> foreach ($FL_Item in $FileList)

输出一个与列表中任何目录都不匹配的文件...

WARNING: 
WARNING: No matching directory was found for [ 640px Elian Web heat.jpg ].
WARNING:     The file was not moved.