基于文件名移动文件



我希望根据文件名的后半部分移动文件。文件看起来像这样

43145123_Stuff.zip
14353135_Stuff.zip
2t53542y_Stuff.zip
422yg3hh_things.zip

我只想移动以Stuff.zip结尾的文件到目前为止,我在PowerShell中有这个功能,但它只会根据文件名的前半部分移动文件。

#set Source and Destination folder location
$srcpath = "C:PowershelltestSource"
$dstpath = "C:PowershelltestDestination"
#Set the files name which need to move to destination folder
$filterLists = @("stuff.txt","things")

#Get all the child file list with source folder
$fileList = Get-ChildItem -Path $srcpath -Force -Recurse
#loop the source folder files to find the match
foreach ($file in $fileList)
{
#checking the match with filterlist
foreach($filelist in $filterLists)
{
#$key = $file.BaseName.Substring(0,8)
#Spliting value before "-" for matching with filterlists value
$splitFileName = $file.BaseName.Substring(0, $file.BaseName.IndexOf('-'))

if ($splitFileName -in $filelist)

{

$fileName = $file.Name

Move-Item -Path $($file.FullName) -Destination $dstpath
}
}
}

状态目标和代码实际做的事情之间似乎存在一些差异。这将把文件移动到目标目录。当您确信文件将被正确移动时,从Move-Item命令中删除-WhatIf

$srcpath = "C:PowershelltestSource"
$dstpath = "C:PowershelltestDestination"
Get-ChildItem -File -Recurse -Path $srcpath |
ForEach-Object {
if ($_.Name -match '.*Stuff.zip$') {
Move-Item -Path $_.FullName -Destination $dstpath -WhatIf
}
}

实际上这可以在PowerShell中非常有效地编写(我希望我得到了正确的细节,让我知道):

Get-ChildItem $srcpath -File -Force -Recurse | 
where { ($_.Name -split "_" | select -last 1) -in $filterLists } |
Move-Item $dstpath

或者,如果您想要查找这个特定的过滤器,您可以使用通配符直接指定:

Get-ChildItem $srcpath -Filter "*_Stuff.zip"

最新更新