如何基于PowerShell中的文件扩展创建文件夹

问题描述:

有没有一种方法可以使用PowerShell创建基于文件扩展名的文件夹,并将这些文件移动到这些文件夹中。例如,我有.jpg文件和.txt文件。我希望powershell查看哪些文件是.txt,然后创建一个名为textfiles的文档并将所有.txt文件移动到该文件夹​​中。 我所有的文件都位于C:\ testfiles如何基于PowerShell中的文件扩展创建文件夹

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

我知道这不会使SENCE。真正需要帮助的

我的脚本

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个不同位置的文件。但在我的剧本中,我只给出了一条路径。我怎么可以指定1个多位置

+0

是的,有一种方法。你试过什么了? – Raf 2014-09-26 10:19:07

+0

$ files ='C:\ testfiles \ * .txt' $ foundfiles = Get-ChildItem $ files -Filter * .txt --Force -Recurse new-item $ foundfiles – srk786 2014-09-26 10:23:34

+0

hi raf我刚刚修改问题 – srk786 2014-09-26 10:25:02

你可以做到这一点的步骤:
1.获取所有文件

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


2.看返回propertys

$arr_Files | fl * 


3.现在你看到一个“Extension:.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只返回文件没有文件夹。

+0

我刚刚修改我的脚本 – srk786 2014-09-26 11:05:15

试试这个,它会动态创建的文件列表中的目录中$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

非常好的使用'Join-Path'这就是它的用途。 – Matt 2014-09-26 11:06:08

怎么样的东西有点更优雅?

$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 } 
    } 

这应该做到吗?