我想创建一个函数,根据文件“C:\Users\dGud\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"
}
}
}
}
不言而喻,实现这一目标有很多方法。您可能根本不需要函数,因为这些文件可以直接通过管道传输到
ForEach-Object
循环。无论如何,如果我们正在使用一个函数,我将首先将由Get-ChildItem
生成的[FileInfo]
对象集合发送给该函数。这是在扩展的地方可能看起来像这样:
在您的演示代码中,您有扩展名,但是您手头上没有文件对象,因此没有任何东西可以移动
另一个使用switch语句的变体@AbrahamZinala建议:
显然
Switch
使事情更简洁,但没有描述性。另外,请注意break
语句。与If\ElseIf
不同的是Switch
语句将计算多个条件和脚本块。我们用Break
停止这种行为不是多余的,但这里还有很多事情可以做。例如,我们可以通过管道启用函数,以便它可以在
Get-ChildItem
之后立即通过管道传输,但考虑到前面提到的ForEach-Object
的潜力也会运行得差不多,这可能不值得带有
ForEach-Object
的示例:注意:我不会在
ForEach-Object
脚本块中使用Switch
$_
在Switch
上下文中的操作不同注:所有这些都未经测试。您可能需要对
-Path
参数使用.FullName
属性,可以是$File.FullName
或$_.FullName
。*-Item
cmdlet可能会以这种方式过于挑剔我想这就是你要找的。此函数只接受文件作为输入,请注意,我使用的是下面的
Get-ChildItem -File
。另一点需要考虑的是,如果在目标文件夹中存在一个具有相同名称的^ {< CD2>},{{CD3>}将抛出以下错误:Move-Item : Cannot create a file when that file already exists.
如果要替换现有文件,可以使用
-Force
,如果存在同名的现有文件,可以在其中添加新条件如何使用该功能:
如果扩展总是映射到这些路径,那么可以将它们存储在哈希表中
相关问题 更多 >
编程相关推荐