【问题标题】:Powershell: Extracting parts of file name to create folders and move files into the folderPowershell:提取部分文件名以创建文件夹并将文件移动到文件夹中
【发布时间】:2021-10-21 08:14:42
【问题描述】:

我是 powershell 的新手,我正在努力实现以下目标:

我有一个格式相同的文件列表:SURNAME_FIRSTNAME_CODE1_CODE2_NAME.pdf/docx 等

我想创建一个名为:SURNAME FIRSTNAME CODE1 的子文件夹

然后将所有这些相关文件移动到文件夹中。

我设法找到一篇文章来处理第一部分(即 SURNAME),但不确定如何使它与其他部分一起工作......任何帮助将不胜感激。

这是我目前所拥有的:(感谢一位海报伙伴)

Get-ChildItem -File -Path $directory -Filter "*.*" | 
ForEach-Object {
New-Item -ItemType Directory "$directory$($_.Name.Split("_")[0])" -Force;   
Move-Item -Path $_.FullName -Destination  "$directory$($_.Name.Split("_")[0])\$($_.Name)"      
} 

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    我就是这样做的。它使用Group-Object 对属于同一目录的文件进行分组,并使用format operator 创建目录名称。如果您有任何问题,请告诉我。

    Get-ChildItem $directory -File |
      group { "{0} {1} {2}" -f $_.BaseName.Split("_") } |
      foreach {
        $newDir = Join-Path $directory $_.Name
        New-Item $newDir -ItemType Directory
        $_.Group | Move-Item -Destination $newDir
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      相关资源
      最近更新 更多