有谁可以帮助我自动根据文件名称将文件移动到文件夹中?
请看截图。
查询:如何根据文件创建不带编号和扩展名的文件夹。(例如,Alpha Wong)并将所有文件(Alpha Wong_1.jpg...Alpha Wong_7.jpg)移动到其中。
谢谢。
答案1
尝试下面的操作,这是 PowerShell:
$folderPath = "C:\Path\to\folder"
# Get all files in the folder
$files = Get-ChildItem -Path $folderPath -File
# Loop through each file
foreach ($file in $files) {
# Split the file name using the underscore character
$fileNameParts = $file.Name.Split("_")
if ($fileNameParts.Count -gt 1) {
# Extract the folder name from the file name parts
$folderName = $fileNameParts[0]
# Check if the folder exists
$folderExists = Test-Path -Path (Join-Path -Path $folderPath -ChildPath $folderName) -PathType Container
if ($folderExists) {
Write-Host "Folder '$folderName' exists for file '$($file.Name)'."
} else {
# Create the folder
$newFolderPath = Join-Path -Path $folderPath -ChildPath $folderName
New-Item -Path $newFolderPath -ItemType Directory | Out-Null
Write-Host "Created folder '$folderName' for file '$($file.Name)'."
}
# Move the file to the folder
$destinationPath = Join-Path -Path $folderPath -ChildPath $folderName
$destinationFile = Join-Path -Path $destinationPath -ChildPath $file.Name
Move-Item -Path $file.FullName -Destination $destinationFile
Write-Host "Moved file '$($file.Name)' to folder '$folderName'."
} else {
Write-Host "Invalid file name format: $($file.Name)."
}
}
如果文件夹不存在,此脚本将创建该文件夹并将文件移动到该文件夹中。它首先检查文件夹是否存在,如果不存在,则使用 New-Item cmdlet 创建该文件夹。然后,它使用 Move-Item cmdlet 将文件移动到新建或现有的文件夹中。
请确保将“C:\Path\to\folder”替换为文件夹的实际路径。