我在名为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
}
答案 0 :(得分:1)
以下内容应根据您的条件移动文件。如果您对要移动的内容感到满意,请删除-WhatIf
开关。
$Source = "D:\TestARC_Source"
$Dest = "D:\TestARC_Destination"
$FilesToMove = Get-ChildItem -Path $Source -File -Recurse -Filter "*.dat" -Include "[0-9][0-9]*"
Foreach ($file in $FilesToMove) {
Move-Item -Path $file -Destination "$Dest\File_$($file.basename.substring(0,2))” -WhatIf
}
答案 1 :(得分:0)
一种有效的方法是按前两位数字对文件进行分组,
检查文件夹是否存在(并在必要时创建),然后一次性移动文件。
volume_prices.loaded? # should return true
volume_prices.count # should return 0
volume_prices.length # should return 1
volume_prices.reload.length # should return 0
使用上述测试数据运行后的树:
## Q:\Test\2019\05\31\SO_56397901.ps1
$SourceFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Source\"
$targetFolder = "C:\Users\Administrator\Desktop\ARC_Testing\TestARC_Destination\"
Get-ChildItem -Path "$SourceFolder[0-9][0-9]*" -Filter *.dat |
Group-Object {"file_"+$_.BaseName.Substring(0,2)}| ForEach-Object {
$TargetDir = Join-Path $targetFolder $_.Name
if(!(Test-Path $TargetDir)){MD $TargetDir | Out-Null}
$_.Group.FullName | Move-Item -Destination $TargetDir #-WhatIf
}