【发布时间】:2019-10-17 06:28:23
【问题描述】:
我在名为 D:\TestARC_Source 的目录中有数百个类似以下的 excel 文件
5020190429.dat
5120190429.dat
602019111121.dat
702019050926.dat
etc.
我需要一个脚本来根据文件名的前两个字符将它们移动到相应的文件夹中。文件夹已在目标目录上创建。
D:\TestARC_Destination\file_50
D:\TestARC_Destination\file_51
D:\TestARC_Destination\file_60
D:\TestARC_Destination\file_70
文件应根据文件名的前两个字符移动到相应的文件夹。例如5020190429.dat 移动到50_file 文件夹。
我正在尝试编辑下面的脚本,但它不起作用。我对 PS 脚本知之甚少,如果您能帮助我,我将不胜感激。
$SourceFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Source\"
$targetFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Destination\"
# Find all files matching *.sql in the folder specified
Get-ChildItem -Path $SourceFolder -Filter *.dat | ForEach-Object {
# Combine the source filename and target directory
# The source filename has all instances of _ replaced with \
# Cast the resulting string to a FileInfo object to take advantage of extra methods
[System.IO.FileInfo]$destination = (Join-Path -Path $targetFolder -ChildPath $_.Name.replace("_","\"))
# Create the directory if it doesn't already exits
if (!(Test-Path) $destination.Directory.FullName)
{
New-item -Path $destination.Directory.FullName -ItemType Directory
}
# Copy the source to the target directory
copy-item -Path $_.FullName -Destination $Destination.FullName
}
【问题讨论】:
-
您的文字和示例不同,方案是
file_50还是50_file?你的标题也会移动,而你的代码会复制? -
嗨..对不起我的错误解释。实际上文件夹名称是 50_file 而不是 file_50。其他 53_file、60_file 和 70_file 也是如此。我们能否再添加一项功能,如果出现任何其他文件(如 14、20 等)并且该文件夹在目标中不可用,它应该将文件保留在源文件夹中。谢谢你,很抱歉造成混乱:)
标签: powershell