[英]Create folders and move files to folder structure based on filename
我有一個包含視頻文件的文件夾,我需要為每個文件創建一個文件夾,該文件夾的名稱與該文件的名稱相同(減去文件擴展名),然后將該特定文件移至與其關聯的文件夾中。
最終結果應消除根目錄中的所有文件,並且每個文件夾應包含一個文件。
示例文件夾應如下所示開始:
然后看起來像這樣:
除了將文件移動到其關聯的文件夾的最后一步之外,所有其他操作均正常。
在第二個ForEach
我嘗試使用第一個循環中使用的$basename
變量指定目標路徑。 這不起作用,因為它導致將所有文件移動到一個文件夾中,這是從第一個Foreach循環傳遞到$basename
變量的最后一個對象。
foreach ($filename in $VideoFiles) {
Move-Item -Path \\server1\Video\Staging\$filename -Destination \\server1\Video\Staging\$basename -verbose
}
這種方式很有意義,但是由於我有限的知識和經驗,我無法找到實現目標的另一種方法。 我開始研究嵌套的ForEach循環,但是我猜想有一種更簡單的方法可以完成此操作。
我在第二個循環中嘗試了以下命令
Move-Item -Path \\server1\Video\Staging\$filename -Destination \\server1\Video\Staging\$filename -verbose
但是,當然,該變量存儲文件名(包括擴展名),並且不移動任何文件。
任何幫助將不勝感激..!
Get-ChildItem -Path \\server1\video\staging | ForEach-Object {$_.basename} | Out-File \\server1\video\videonames.txt
$VideoNames = Get-Content \\server1\video\videonames.txt
Get-ChildItem -Path \\server1\video\staging | ForEach-Object {$_.name} | Out-File \\server1\video\videosfiles.txt
$VideoFiles = Get-Content \\server1\video\videosfiles.txt
foreach ($BaseName in $VideoNames) {
New-Item -ItemType Directory -Path \\server1\Video\Staging\$BaseName
}
foreach ($filename in $VideoFiles) {
Move-Item -Path \\server1\Video\Staging\$filename -Destination \\server1\Video\Staging\$basename -verbose
}
這可能不是執行此操作的最佳方法,但它確實可以滿足我的需要。 我太專注於使用確切的文件名,包括文件名和通配符滿足要求時的.ext。
#Creates a text file list of the file names and defines a variable for it.
Get-ChildItem -Path \\server1\video\staging | ForEach-Object {$_.basename} | Out-File \\server1\video\videonames.txt
$VideoNames = Get-Content \\server1\video\videonames.txt
#Creates the folder structure based on file names
$Folder = foreach ($BaseName in $VideoNames){
New-Item -ItemType Directory -Path \\server1\Video\Staging\$BaseName
}
#Moves each file in the folder with the same name.
foreach ($File in $VideoNames){
Move-Item -Path \\server1\Video\Staging\$file.* -Destination \\server1\Video\Staging\$file -verbose
}
您的回答很好,但是無需創建帶有屬性名稱的文件。
您可以在循環內選擇BaseName
屬性,這意味着您只需要一個foreach
:
$Source = '\\server1\Video\Staging'
foreach ($File in Get-ChildItem -Path $Source) {
$FileBaseName = $File.BaseName
if(!(Test-Path $Source\$FileBaseName)){
New-Item -ItemType Directory -Path $Source\$FileBaseName -WhatIf
}
Move-Item -Path $Source\$FileBaseName.* -Destination $Source\$FileBaseName -WhatIf
}
注意:如果希望代碼執行操作,請刪除-WhatIf
我將進一步簡化此過程,並在此過程中通過使用Join-Path
cmdlet消除創建錯誤路徑名的風險,如下所示:
$Source = '\\server1\Video\Staging'
(Get-ChildItem -Path $Source -File) | ForEach-Object {
$destination = Join-Path -Path $Source -ChildPath $_.BaseName
if(!(Test-Path $destination)){
New-Item -ItemType Directory -Path $destination | Out-Null
}
$_ | Move-Item -Destination $destination
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.