如何使用 Powershell 根据文件名将文件移动到文件夹和子文件夹?

How to move files to Folder and Sub folder based on file name using Powershell?

这里是 Powershell 初学者。我尝试使用 Powershell 对此进行编码,但一无所获。

我有一个 Wav 文件列表,我需要根据文件名将它们自动移动到文件夹中。

20190822091227_202123545.wav

20190822080957_202123545.wav

文件名决定文件夹结构-示例

2019(This is the Year)08(This is the Month)22(This is the Day)_202123545.wav

因此文件夹结构将是

C:\Archive19(Year)1908(YearMonth)(Day)
C:\Archive191908 

wav 文件将移至该文件夹 - 在本例中为 22

我已经尝试了我在 Whosebug 上找到的这段代码并添加了我自己的代码,但它给我错误。

$SourceFolder = Set-Location "C:\CR\Files"
$targetFolder = "C:\Archive\CR_Dev\Test_Folder"
$numFiles = (Get-ChildItem -Path $SourceFolder -Filter *.WAV).Count
$i=0

clear-host;
Write-Host 'This script will copy ' $numFiles ' files from ' $SourceFolder ' to ' $targetFolder
Read-host -prompt 'Press enter to start copying the files'

$files = Get-ChildItem $SourceFolder | where {$_.extension -in ".wav"} | select -expand basename

 # Out FileName, year and month
    $Year = $files.Substring(0,4)
    $Month = $files.Substring(4,2)
    $Day = $files.Substring(6,2)

foreach ($file in $files)

{

    # Set Directory Path
    $Directory = $targetFolder + "\" + $Year+$Month + "\" + $Day

    # Create directory if it doesn't exsist
    if (!(Test-Path $Directory))
    {
    New-Item $Directory -type Directory
    }

    [int]$percent = $i / $numFiles * 100

    # Move File to new location
    $file | Copy-Item -Destination $Directory

    Write-Progress -Activity "Copying ... ($percent %)" -status $_  -PercentComplete $percent -verbose
    $i++
}

Write-Host 'Total number of files read from directory '$SourceFolder ' is ' $numFiles
Write-Host 'Total number of files that was copied to '$targetFolder ' is ' $i
Read-host -prompt "Press enter to complete..."
clear-host;

文件没有移动到文件夹中,我收到文件名错误

示例

C:\Archive19 201919 08 2019 08 22

$files 被恰当地命名为复数,作为一个可以包含许多文件的变量。 但是当你去检索日期部分时,你使用调用一次,在文件s的整个集合上,而不是在每个单独的$file(这是你的变量在遍历文件集合的循环中。

所以您想在循环中内部设置日期变量,在每次迭代中,以便它与当前文件相关。

$files = Get-ChildItem $SourceFolder | where {$_.extension -in ".wav"} | select -expand basename

foreach ($file in $files)
{
    $Year = $file.Substring(0,4)
    $Month = $file.Substring(4,2)
    $Day = $file.Substring(6,2)

   $Directory = $targetFolder + "\" + $Year+$Month + "\" + $Day

# etc
}

此外,您在问题中设置的模式似乎与您设置的不一样,所以我对您的输出看起来有些困惑。

你这里有:

$Directory = $targetFolder + "\" + $Year+$Month + "\" + $Day

应该产生:C:\Archive1908,即使你想要 C:\Archive191908

要生成您想要的内容,该行应如下所示:

$Directory = $targetFolder + "\" + $Year + "\" + $Year+$Month + "\" + $Day

顺便说一句,你可以直接在双引号字符串中使用变量:

$Directory = "$targetFolder$Year$Year$Month$Day"