简体   繁体   中英

Moving files with powershell by filename numbering

I'm a total noob with powershell but after reading a little I came up with the following code. As you can see I'm using "Write-Output" for testing my code but the final use for it will be moving files to new folders. The files that will be brought to folders are the ones the break the pattern "+2 sequence" so if the files names are "x_x_0002,x_x_0004,x_x_0006,x_x_0008,x_x_0012,x_x_0016,x_x_0018,x_x_0020..." the selected files will be "x_x_0008,x_x_0012,x_x_0018" and those will move to a folder named by number of the last file in the group, "18 in this example (probably I should think for a sequential folder naming but I can solve after this). I'm close but this code fails on the last two items from the group, my approach skips the second to last one. I hope someone could lend me a hand. Thanks, and pardon my english:$

$Source = "G:\output\test"
$oldNum = 0
$sfiles = @()
Get-ChildItem $Source | ForEach-Object{
    $cropTxt = $_.Basename.Split("_")[2]
    $currNum = [convert]::ToInt32($cropTxt, 10)
    $diff = $currNum - $oldNum
    If ($diff -eq $currNum) {
        $oldNum = $currNum
    }
    else{
        if ($diff -eq 2) {
            if($sfiles.Count -ne 0){
                $sfiles += $currNum
                $sfiles += "----"
                $sfiles | ForEach-Object {
                    Write-Output $_
                }
                $sfiles = @()
            }
        }
        else{
            $sfiles += $oldNum
        }
        $oldNum = $currNum
    }
}

Solved!

$Source = "G:\output\test"
$oldNum = 0
$currFolder = 18
$sfiles = @()
Get-ChildItem $Source | ForEach-Object{
    $cropTxt = $_.Basename.Split("_")[2]
    $currNum = [convert]::ToInt32($cropTxt, 10)
    $currFile = $_.Fullname
    $diff = $currNum - $oldNum
    If ($diff -eq $currNum) {
        $oldNum = $currNum
        $oldFile = $currFile
    }
    else{
        if ($diff -eq 2) {
            if($sfiles.Count -ne 0){
                #$sfiles += $oldNum
                #$sfiles += "----"
                $sfiles += $oldFile
                New-Item -Path "$Source\$currFolder" -ItemType Directory
                $sfiles | ForEach-Object {
                    move-item -Path $_ -Destination "$Source\$currFolder"
                }
                $currFolder = $currFolder + 1
                $sfiles = @()
            }
        }
        else{
            $sfiles += $oldFile
        }
        $oldNum = $currNum
        $oldFile = $currFile
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM