我需要将许多文件复制到不同的文件夹中。我的文件如下所示:
aaa_280_,aaa_281_,aaa_282_
它们都位于一个源文件夹中。目标文件夹如下所示:
xy_280,xy_281,...
此代码适用于 powershell 中的复制过程:
copy-item "Source\*" "destination\xy_280" -Filter "aaa_280*
有没有办法可以循环遍历所有文件,并使用递增值“+1”,以便每次成功复制后目标和过滤器都会增加?谢谢
答案1
正如我的评论。
Clear-Host
Get-ChildItem -Path 'D:\Temp' -Filter 'abc*' |
FOrEach-Object {
New-Item -Path 'D:\Temp' -ItemType Directory -Name $PSItem.BaseName -WhatIf
Copy-Item -Path $PSItem.FullName -Destination "D:\Temp\$($PSItem.BaseName)" -WhatIf
}
# Results
<#
What if: Performing the operation "Create Directory" on target "Destination: D:\Temp\abc - Copy - Copy".
What if: Performing the operation "Copy File" on target "Item: D:\Temp\abc - Copy - Copy.bat Destination: D:\Temp\abc - Copy - Copy".
What if: Performing the operation "Create Directory" on target "Destination: D:\Temp\abc - Copy".
What if: Performing the operation "Copy File" on target "Item: D:\Temp\abc - Copy.bat Destination: D:\Temp\abc - Copy".
What if: Performing the operation "Create Directory" on target "Destination: D:\Temp\abc".
What if: Performing the operation "Copy File" on target "Item: D:\Temp\abc.bat Destination: D:\Temp\abc".
What if: Performing the operation "Create Directory" on target "Destination: D:\Temp\ABC_123".
What if: Performing the operation "Copy File" on target "Item: D:\Temp\ABC_123.xls Destination: D:\Temp\ABC_123".
#>
只需删除-WhatIf
它就可以了。
答案2
现在可以正常工作,但有警告:
> Clear-Host
>> Get-ChildItem -Path 'D:\source' -Filter 'abc_*' |
>> FOrEach-Object {
>> New-Item -Path 'D:\destination' -ItemType Directory -Name $PSItem.BaseName.Substring(8,3)
>> Copy-Item -Path $PSItem.FullName -Destination "D:\destiantion\$($PSItem.BaseName.Substring(8,3))"
>> }
使用子字符串,我能够隔离和分组需要放入同一文件夹的所有文件。我认为出现错误消息是因为在将第一个文件复制到目标文件夹后,目标文件夹已经存在。
再次感谢。