首页 > 解决方案 > Powershell将所有下载移动到另一个文件夹功能

问题描述

我想创建一个函数来根据文件类型将文件移动到文件夹“C:\Users\dgoud\Desktop\TP4\Telechargement”到特定文件夹

我想为 PowerShell 提供等价物:

for root, dirs, files in os.walk("C:\Users\dgoud\Desktop\TP4\Telechargement"):

我的 PowerShell 函数:

 function DeplacerDansBonDossier {
            param (
                $extension
            )

        foreach ($file in $files) {
            $extn = [IO.Path]::GetExtension($line)
            if ($extn -eq ".txt" )
            {
                Move-Item -Path "C:\Users\dgoud\Desktop\TP4\Documents"
            }

            elseif ($extn -eq ".mp3" )
            {
                Move-Item -Path "C:\Users\dgoud\Desktop\TP4\Musique"
            }

            elseif ($extn -eq ".wav" )
            {
                Move-Item -Path "C:\Users\dgoud\Desktop\TP4\Musique"
            elseif ($extn -eq ".mp4" )
            {
                Move-Item -Path "C:\Users\dgoud\Desktop\TP4\VidBo"
            }

            elseif ($extn -eq ".mkv" )
            {
                Move-Item -Path "C:\Users\dgoud\Desktop\TP4\VidBo"
            }
        }
    }
}

标签: pythonpowershell

解决方案


我想这就是你要找的。这个函数只接受文件作为输入,注意我在Get-ChildItem -File下面使用。要考虑的另一点是,如果File目标文件夹上有同名的文件夹Move-Item,则会抛出以下错误:

Move-Item : Cannot create a file when that file already exists.

如果-Force要替换现有文件,或者如果存在同名的现有文件,则可以在其中添加新条件。

function DeplacerDansBonDossier {
[cmdletbinding()]
param(
    [parameter(mandatory,valuefrompipeline)]
    [System.IO.FileInfo]$File
)

    begin
    {
        $Paths = @{
            Documents = "C:\Users\dgoud\Desktop\TP4\Documents"
            Music = "C:\Users\dgoud\Desktop\TP4\Musique"
            Video = "C:\Users\dgoud\Desktop\TP4\VidBo"
        }
    }
    
    process
    {
        switch -Regex($File.Extension)
        {
            '^\.txt$'{
                $File | Move-Item -Destination $Paths['Documents']
                Write-Verbose ('Moved {0} to {1}' -f $file.Name,$Paths['Documents'])
                break
            }

            '^\.mp3$|^\.wav$'{
                $File | Move-Item -Destination $Paths['Music']
                Write-Verbose ('Moved {0} to {1}' -f $file.Name,$Paths['Music'])
                break
            }

            '^\.mp4$|^\.mkv$'{
                $File | Move-Item -Destination $Paths['Video']
                Write-Verbose ('Moved {0} to {1}' -f $file.Name,$Paths['Video'])
                break
            }
        }
    }
}

如何使用该功能:

Get-ChildItem 'C:\Users\dgoud\Desktop\TP4\Telechargement' -File | DeplacerDansBonDossier

# If you want to see which Files are being moved and their destination
# you can use -Verbose
Get-ChildItem 'C:\Users\dgoud\Desktop\TP4\Telechargement' -File | DeplacerDansBonDossier -Verbose 

推荐阅读