Move a files that have the same name but different

2019-07-11 11:08发布

I am a junior tech and have been tasked to write a short powershell script. The problem is that I have started to learn the PS 5 hours ago - once my boss told that I'm assigned to this task. I'm a bit worried it won't be completed for tomorrow so hope you guys can help me a bit. The task is:

I need to move the files to different folders depending on certain conditions, let me start from the he folder structure:

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.

The job is to move files from c:\LostFiles to appropiate folders in c:\Media folder tree if

The name of the file from c:\LostFiles corresponds to a file name in one of the subfolders of the C:\media We must ignore the extension, for example:

C:\LostFiles has these files which we need to move (if possible) : imageFlower.png, videoMarch.mov, danceRock.bmp

C:\Media\Flowers\ has already this files: imageFlower.bmp, imageFlower.mov

imageFlower.png should be moved to this folder (C:\media\Flowers) because there is or there are files with exactly the same base name (extension must be ignored)

Only the files that have corresponding files (the same name) should be moved.

So far I have written this piece of code (I know it is not much but will be updating this code as I am working on it now (2145 GMT time). I know I missing some loops, hey yeah, I am missing a lot!

#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条回答
smile是对你的礼貌
2楼-- · 2019-07-11 11:16

You could build a hashtable from the media files, then iterate through the lost files, looking to see if the lost file's name was in the hash. Something like:

# 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] }  }
查看更多
登录 后发表回答