【问题标题】:Powershell - Create a folder from a file name, then place that file in the folderPowershell - 从文件名创建一个文件夹,然后将该文件放在文件夹中
【发布时间】:2017-05-18 23:46:27
【问题描述】:

我有一个文件列表说...

T123_Product_1.jpg
T123_Product_2.jpg
T123_Product_3.jpg
T456_Product_1.jpg
T456_Product_2.jpg
T456_Product_3.jpg 

等等。等等等等,大约还有 900 个文件

我需要做的是根据第一个下划线之前的字符创建一个文件夹,但不要重复它,因为有多个文件。

所以在上面的示例中,我只想要两个名为 T123 和 T456 的文件夹。

然后我需要脚本将适当的文件放在文件夹中。

我在这个帖子中找到了一些代码,但它们并不完全符合我的要求。

https://superuser.com/questions/306890/windows-batch-script-to-create-folder-for-each-file-in-a-directory-name-it-tha

    $Files = Get-ChildItem -Path 'C:\Info\AUGUST 2011\Checklists\' -Filter 'DET1__*'
$Files | ForEach-Object {
    $FileFullName = $_.FullName
    $TempFileName = "$($FileFullName).tmp"
    $DestinationFileName = "$FileFullName\$($_.Name)"
    Move-Item $FileFullName $TempFileName
    New-Item -Path $FileFullName -ItemType Directory
    Move-Item $TempFileName $DestinationFileName
}

有什么帮助吗?

【问题讨论】:

  • 嗨,你试过什么?
  • 我正在查看此代码,来自我发现的另一个线程,但不完全是它。这就是上面的代码所做的。创建一个文件夹,将文件名的其余部分(在 DET1__ 之后)作为文件夹的标题将该文件移动到该特定文件夹 @sodawillow

标签: file powershell directory naming


【解决方案1】:

也试试。

cd <path to your folder>
  $files = Get-ChildItem -file;
  ForEach ($file in $files)
  {
    $folder = New-Item -type directory -name ($file.BaseName -replace "_.*");
    Move-Item $file.FullName $folder.FullName;
  }

您也可以在 $file.BaseName 上使用 Substring 方法。

cd <path to your folder>
$files = Get-ChildItem -file;
ForEach ($file in $files)
{
  $fileName = $file.BaseName;
  $folder = New-Item -type directory -name $fileName.Substring(0, $fileName.Length-10);
  Move-Item $file.FullName $folder.FullName;
}

The same posted here with explanation.

【讨论】:

    【解决方案2】:
    $directory="c:\temp\"
    
    #explicit and long version
    Get-ChildItem -File -Path $directory -Filter "*.jpg" | 
    ForEach-Object {
    New-Item -ItemType Directory "$directory$($_.Name.Split("_")[0])" -Force;   
    Move-Item -Path $_.FullName -Destination  "$directory$($_.Name.Split("_")[0])\$($_.Name)"      
    }
    
    #short version 
    gci -File -Path $directory -Fi "*.jpg" | 
    %{ ni -ItemType Directory "$directory$($_.Name.Split("_")[0])" -Force;mvi $_.FullName "$directory$($_.Name.Split("_")[0])\$($_.Name)" }
    

    【讨论】:

      【解决方案3】:

      这里最简单的方法是按第一部分分组文件,这将成为目录名称。在典型的 PowerShell 管道方式中,这是相当简洁的:

      Get-ChildItem -File |  # Get files
        Group-Object { $_.Name -replace '_.*' } |  # Group by part before first underscore
        ForEach-Object {
          # Create directory
          $dir = New-Item -Type Directory -Name $_.Name
          # Move files there
          $_.Group | Move-Item -Destination $dir
        }
      

      【讨论】: