移动名称相同但扩展名不同的文件。Powershell [英] Move a files that have the same name but different extension. Powershell

查看:15
本文介绍了移动名称相同但扩展名不同的文件。Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是初级技术人员,任务是编写一个简短的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:介质文件夹树中的相应文件夹,如果

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

C:LostFiles有以下我们需要移动的文件(如果可能):ImageFlower.png、VideoMarch.mov、danceRock.bmp

C:MediaFlowers已经有这个文件:ImageFlower.bmp、ImageFlower.mov

应将ImageFlower.png移到此文件夹(C:mediaFlowers),因为存在或存在具有完全相同基本名称的文件(必须忽略扩展名)

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

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

#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

        }

推荐答案

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

# 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] }  }

这篇关于移动名称相同但扩展名不同的文件。Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆