Powershell-从文件名创建一个文件夹,然后将该文件放在文件夹中 [英] Powershell - Create a folder from a file name, then place that file in the folder

查看:103
本文介绍了Powershell-从文件名创建一个文件夹,然后将该文件放在文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a list of files say...

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个文件

etc. etc. etc. for about 900 more files

我需要做的是根据第一个下划线之前的字符创建一个文件夹,但由于有多个文件,因此不再重复.

What I am needing to do is create a folder based on the characters before the first underscore, but to not repeat it since there are multiple files.

因此,在上面的示例中,我只需要两个名为T123和T456的文件夹.

So in the example above, I would only want two folders named T123 and T456.

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

Then I would need the script to place the appropriate files in the folder.

我在此线程中找到了一些代码,但是它们并不能完全满足我的要求.

I had found some codes in this thread, but they don't exactly do what I'm looking for.

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
}

有帮助吗?

推荐答案

这里最简单的方法是按照第一部分对文件进行分组,然后将其变为目录名.在典型的PowerShell管道方式中,这非常简洁:

The easiest way here would be to group the files by the first part, which will then become the directory name. In typical PowerShell pipeline manner this is fairly succinct:

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
  }

这篇关于Powershell-从文件名创建一个文件夹,然后将该文件放在文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆