如何在powershell中基于文件扩展名创建文件夹

时间:2014-09-26 10:18:01

标签: powershell

我们是否可以使用powershell基于文件扩展名创建文件夹,而不是将这些文件移动到这些文件夹中。例如,我有.jpg文件和.txt文件。我想powershell查看哪些文件是.txt,然后创建一个名为textfiles的文件,并将所有.txt文件移动到该文件夹​​中。 我的所有文件都位于C:\ testfiles

$files = 'C:\testfiles\*.txt'
$foundfiles = Get-ChildItem $files -Filter *.txt -Force -Recurse
new-item $foundfiles -type directory

我知道它没有成功。真的需要帮助

我的剧本

Get-ChildItem 'C:\testfiles' -Filter *.txt | Where-Object {!$_.PSIsContainer} | Foreach-Object{

$dest = Join-Path $_.DirectoryName $_.BaseName.Split()[0]

if(!(Test-Path -Path $dest -PathType Container))
{
    $null = md $dest
}

$_ | Move-Item -Destination $dest -Force
}

这很完美,但问题是我有10个不同位置的文件。但在我的剧本中,我只给出了一条路。我怎样才能指定多个位置

3 个答案:

答案 0 :(得分:1)

试试这个,它将从$roots

中的文件列表中动态创建目录
$roots = @("d:\temp\test","C:\testfiles")

foreach($root in $roots){
    $groups = ls $root | where {$_.PSIsContainer -eq $false} | group extension
    foreach($group in $groups){
        $newPath = Join-Path $root ($group.Name.Substring(1,($group.Name.length - 1)))
        if( (Test-Path $newPath) -eq $false){
            md $newPath | Out-Null
        }
        $group.Group | Move-Item -Destination $newPath
    }
}

答案 1 :(得分:0)

您可以执行以下步骤:
1.获取所有文件

#Get all files
[ARRAY]$arr_Files = Get-ChildItem -Path "C:\temp" -Recurse -Force


2.看看退回的物业

$arr_Files | fl *


3.现在你看到了一个"扩展名:.zip"。因此,您可以查看此文件夹是否存在,何时不存在然后创建它。在此之后,将文件移动到文件夹中。

#For each file
Foreach ($obj_File in $arr_Files) {

    #Test if folder for this file exist
    If (!(Test-Path -Path "C:\Temp$($obj_File.Extension)")) {
        New-Item -Path "C:\Temp$($obj_File.Extension)" -ItemType Directory
    }  

    #Move file
    Move-Item -Path $obj_File.FullName -Destination "C:\Temp$($obj_File.Extension)\$($obj_File.Name)"
}


现在你必须看看Get-ChildItem -Path "C:\temp" -Recurse -Force只返回没有文件夹的文件。

答案 2 :(得分:0)

一些更优雅的东西怎么样?

$Files = GCI c:\testfiles\
$TXTPATH = <PATH>
$JPGPATH = <PATH>
Switch ($Files){
    {$_.Extension -eq '.TXT' } { move-item $_.fullname $TXTPATH -force }
    {$_.Extension -eq '.JPG' } { move-item $_.fullname $JPGPATH -force }
    }

应该这样做吗?