[英]Move files based on partial file name from array
I am trying to move files based on a list of prefix from a text file to match a portion of the actual files which are dynamically generated. 我试图根据文本列表中的前缀列表移动文件,以匹配动态生成的实际文件的一部分。
Example of prefix in text file: 文本文件中的前缀示例:
103 1stCity 25 2ndCity 302 3rdCity
There are no commas and each city is a new line in the text file (not CSV format). 没有逗号,每个城市在文本文件中都是换行符(不是CSV格式)。
Example of files to search: 要搜索的文件示例:
103 1stCity 20170901 12387.txt 129 OtherCity 20170905 354568.txt
Here is what I have: 这是我所拥有的:
$file_list = Get-Content "P:\some\path\to\PrefixOfClientNames.txt"
$search_folder = "J:\FilesToSearch_SomeStayHere"
$destination_folder = "J:\SomeFilesGetMovedHere"
foreach ($file in $file_list) {
$file_to_move = Get-ChildItem -Path $search_folder |
Where-Object { $_.Name -like $file }
if ($file_to_move) {
Move-Item $file_to_move $destination_folder -WhatIf
}
If all matching files should go to the same destination folder you'd build a regular expression from the prefix file and anchor it at the beginning of the string: 如果所有匹配的文件都应转到相同的目标文件夹,则可以从前缀文件构建一个正则表达式并将其锚定在字符串的开头:
$prefixes = Get-Content 'P:\some\path\to\PrefixOfClientNames.txt' |
ForEach-Object { [regex]::Escape($_) }
$pattern = '^{0}' -f ($prefixes -join '|')
then use a pipeline for moving matching files: 然后使用管道移动匹配的文件:
Get-ChildItem -Path $search_folder | Where-Object {
$_.Name -match $pattern
} | Move-Item -Destination $destination_folder -WhatIf
Other method 其他方法
$file_list = Get-Content "C:\Temp\prefix.txt" | %{$_ + '*'}
$search_folder = "C:\Temp\searchfolder"
$destination_folder = "C:\Temp\searchfolder"
Get-ChildItem $search_folder -file -Recurse | %{
$name=$_.BaseName
$fullname=$_.FullName
if (($file_list | where { $name -like $_} | select -First 1).Count -gt 0)
{
Move-Item $fullname $destination_folder -WhatIf
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.