移动具有相同名称但扩展名不同的文件。电源外壳

时间:2015-12-22 22:03:22

标签: powershell powershell-v3.0

我是一名初级技术人员,他的任务是撰写简短的PowerShell脚本。问题是我5小时前就已经开始学习PS了 - 一旦我的老板说我已经完成了这项任务。我有点担心它明天没有完成,所以希望你们能帮助我一点。任务是:

我需要根据特定条件将文件移动到不同的文件夹,让我从他的文件夹结构开始:

c:\LostFiles: This folder includes a long list of .mov, .jpg and .png files
c:\Media: This folder includes many subfolders withe media files and projects.

作业是将文件从c:\ LostFiles移动到适用于c:\ Media文件夹树中的文件夹

c:\ LostFiles中文件的名称对应于C:\ media子文件夹中的一个文件名我们必须忽略该扩展名,例如:

C:\ LostFiles有我们需要移动的这些文件(如果可能):imageFlower.png,videoMarch.mov,danceRock.bmp

C:\ Media \ Flowers \已有此文件:imageFlower.bmp,imageFlower.mov

imageFlower.png应该移动到此文件夹(C:\ media \ Flowers),因为存在或者存在具有完全相同基本名称的文件(必须忽略扩展名)

只应移动具有相应文件(同名)的文件。

到目前为止,我已经编写了这段代码(我知道它不多,但会更新此代码,因为我正在处理它(格林尼治标准时间2145)。我知道我错过了一些循环,嘿是的,我是错过了很多!

#This gets all the files from the folder
$orphans = gci -path C:\lostfiles\ -File | Select Basename 

#This gets the list of files from all the folders
$Files = gci C:\media\ -Recurse -File | select Fullname

#So we can all the files and we check them 1 by 1
$orphans | ForEach-Object {

#variable that stores the name of the current file
    $file = ($_.BaseName) 

#path to copy the file, and then search for files with the same name but only take into the accont the base name        
        $path = $Files | where-object{$_ -eq $file} 

#move the current file to the destination
        move-item -path $_.fullname -destination $path -whatif

        }

1 个答案:

答案 0 :(得分:0)

您可以从媒体文件构建哈希表,然后遍历丢失的文件,查看丢失的文件名是否在哈希中。类似的东西:

# Create a hashtable with key = file basename and value = containing directory
$mediaFiles = @{}
Get-ChildItem -Recurse .\Media | ?{!$_.PsIsContainer} | Select-Object BaseName, DirectoryName | 
ForEach-Object { $mediaFiles[$_.BaseName] = $_.DirectoryName }

# Look through lost files and if the lost file exists in the hash, then move it
Get-ChildItem -Recurse .\LostFiles | ?{!$_.PsIsContainer} | 
ForEach-Object { if ($mediaFiles.ContainsKey($_.BaseName)) { Move-Item -whatif $_.FullName $mediaFiles[$_.BaseName] }  }
相关问题