[英]Sorting files into directories with powershell
我有以下问题,如果我能在这方面得到一些帮助,我将不胜感激。 我将 xml 个文件源源不断地放入一个文件夹中。 XML 文件名可能如下所示。 它只上升到 1005。
1001.order-asdf1234.xml
1002.order-asdf4321.xml
我想将文件分类到不基于文件名的唯一命名文件夹中。 一个例子是
C:\Directory Path...\Peter (All files starting with 1001 go in there)
C:\Directory Path...\John (All files starting with 1002 go there)
如何创建批处理或 powershell 脚本以连续将文件分类到指定文件夹中? 因为我只有 5 个文件夹,所以我想简单地为每个文件夹指定目标文件夹,而不是精心设计的循环,但我不知道该怎么做。
最简单的方法是创建一个查找哈希表,您可以在其中定义哪个前缀 ('1001'.. '1005') 映射到哪个目标文件夹:
# create a Hasthable to map the digits to a foldername
$folderMap = @{
'1001' = 'Peter'
'1002' = 'John'
'1003' = 'Lucretia'
'1004' = 'Matilda'
'1005' = 'Henry'
}
# set source and destination paths
$rootFolder = 'X:\Where\the\files\are'
$destination = 'Y:\Where\the\files\should\go'
# loop over the files in the root path
Get-ChildItem -Path $rootFolder -Filter '*.xml' -File |
Where-Object { $_.BaseName -match '^\d{4}\.' } |
ForEach-Object {
$prefix = ($_.Name -split '\.')[0]
$targetPath = Join-Path -Path $destination -ChildPath $folderMap[$prefix]
$_ | Move-Item -Destination $targetPath -WhatIf
}
如果您对屏幕上显示的结果感到满意,请移除-WhatIf
安全开关
您可以使用switch
语句根据文件名的第一部分决定目标文件夹:
$files = Get-ChildItem path\to\folder\with\xml\files -Filter *.xml
switch($files)
{
{$_.Name -like '1001*'} {
$_ |Move-Item -Destination 'C:\path\to\Peter'
}
{$_.Name -like '1002*'} {
$_ |Move-Item -Destination 'C:\path\to\John'
}
{$_.Name -like '1003*'} {
# etc...
}
default {
Write-Warning "No matching destination folder for file '$($_.Name)'"
}
}
如果您改变了对循环的看法,我更喜欢将映射存储在哈希表中并循环遍历每个文件的条目:
$files = Get-ChildItem path\to\folder\with\xml\files -Filter *.xml
$targetFolders = @{
'1001' = 'C:\path\to\Peter'
'1002' = 'C:\path\to\John'
'1003' = 'C:\path\to\Paul'
'1004' = 'C:\path\to\George'
'1005' = 'C:\path\to\Ringo'
}
foreach($file in $files){
$targetFolder = $targetFolders.Keys.Where({$file.Name -like "${_}*"}, 'First')
$file |Move-Item -Destination $targetFolder
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.