【问题标题】:how to create a folder based on a file extenstion in powershell如何在powershell中根据文件扩展名创建文件夹
【发布时间】:2014-09-26 10:18:01
【问题描述】:

有没有办法我们可以使用 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 个不同的位置有文件。但在我的脚本中,我只给出了 1 条路径。如何指定多个位置

【问题讨论】:

  • 是的,有办法。到目前为止,您尝试过什么?
  • $files = 'C:\testfiles*.txt' $foundfiles = Get-ChildItem $files -Filter *.txt -Force -Recurse new-item $foundfiles
  • 嗨 raf 我刚刚修改了问题

标签: powershell


【解决方案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
    }
}

【讨论】:

  • 出色地使用了Join-Path,这就是它的用途。
【解决方案2】:

您可以执行以下步骤:
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 只返回文件而不返回文件夹。

【讨论】:

  • 我刚刚修改了我的脚本
【解决方案3】:

来点优雅的怎么样?

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

应该这样吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多