我有這個檔案夾,里面有文本檔案和 jpg 檔案。每個文本檔案都包含諸如
2021-01-12T07:22:14;0;R0010313.JPG
2021-01-12T07:23:03;0;R0010314.JPG
其中 R 編號對應于該名稱的 jpg 檔案。現在,我想讀取每個文本檔案,獲取 jpg 的名稱,然后將 jpg 移動到與文本檔案名稱相同的新檔案夾,然后移動到下一個文本檔案。我設法創建了具有正確名稱的新檔案夾,所以現在我只需要將正確的 jpg 移動到正確的檔案夾中。這是我到目前為止:
$path = "C:\Users\Yo\Desktop\Brunnar" #Path where all the TXT files are
$TxtFiles = Get-ChildItem -Path $path -filter "*.txt"
$JpgFiles = Get-ChildItem -Path $path -filter "*.JPG"
$files = Get-Childitem $path | Where-Object { ! $_.PSIsContainer} #Get all files in the folder
#For each file in this folder
foreach ($file in $files){
## If it is a txt file
if ([io.path]::GetExtension($file.Name) -eq ".txt"){ # If it is a .txt file
$foldername = [io.path]::GetFileNameWithoutExtension($file) #Remove the fileextension in the foldername
if (!(Test-Path "$path\$foldername")){ #If the folder doesn't exist
New-Item "$path\$foldername" -ItemType "directory" #Create a new folder for the file
}
## Move-Item $file.FullName "$path\$foldername" #Move file into the created folder
Get-ChildItem -LiteralPath C:\Users\Yo\Desktop\Brunnar -Filter *.txt -File -Recurse | foreach {
#$fileData = @{
# "File"=$_.FullName;
$content =(Get-Content -LiteralPath $_.FullName -Raw)
#}
if($content -match $JpgFiles.Name){
#move jpg to the new folder
}
}
}
}
uj5u.com熱心網友回復:
看看下面的代碼片段(未測驗)。
它顯示了執行任務所需的所有步驟,但可能需要進行一些調整。
$Path = 'C:\Users\Yo\Desktop\Brunnar'
# Process only the txt files in the direcotry
foreach ($TextFile in (Get-ChildItem -Path "$($Path)\*.txt" -File)) {
# Get the content of the text file
$Content = Get-Content -Path $TextFile.FullName
# Get the r number from content
$JPGFileName = $Content.Split(';')[2]
# Create folder if not exists
if (-not (Test-Path -Path "$($Path)\$($TextFile.BaseName)")) {
New-Item -Path "$($Path)\$($TextFile.BaseName)" -ItemType Directory
}
# Move the jpg file to the new path
if (Test-Path -Path "$($Path)\$($JPGFileName)") {
Move-Item -Path "$($Path)\$($JPGFileName)" -Destination "$($Path)\$($TextFile.BaseName)\$($JPGFileName)"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/399967.html
上一篇:傳遞用戶引數并回退到默認值
