python - 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"
}
}
}
}
解决方案
我想这就是你要找的。这个函数只接受文件作为输入,注意我在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
推荐阅读
- javascript - 有没有办法保持第三个 div 固定
- java - 使用 Android 设备测量心率
- android - 我无法将数据一张表插入房间的另一张表
- python - 如何获取硒python中的所有href值
- c# - 如何在 c# 中从 fcm 发送数百万个推送通知
- java - 多线程程序中的nullpointerexception问题
- api - Flask API 可选参数不起作用
- javascript - 用于 Wordpress 嵌入式小部件和全屏容器的 React.JS 插件
- spring-boot - @Counted 如何在 Spring Boot 中工作?
- mongodb - 安装 go mongodb 驱动有问题