简体   繁体   中英

Move files based on odd number in file name - powershell

I'm trying to move files with odd numbers at the end of the filename from one folder to another but it doesn't seem to work. I've tried using if statements and for loops no to avail. Some pointers would be much appreciated. My attempts are below..

$srcpath = "C:\Folder\SubFolder3"
$dstpath = "C:\Folder\SubFolder2"
Get-ChildItem -File -Recurse -Path $srcpath |
    ForEach-Object {
        if($_.Name -match '*1.txt', '*3.txt', '*5.txt', '*7.txt', '*9.txt') {
            Move-Item -Path $_.FullName -Destination $dstpath
        }
    }
$srcpath = "C:\Folder\SubFolder3"
$dstpath = "C:\Folder\SubFolder2"
$files = $srcpath
foreach ($file in $files) {
    if ($file -like '*1.txt', '*3.txt', '*5.txt', '*7.txt', '*9.txt') {
        Move-Item -Destination $dstpath
    }
}

I believe the -match operator only returns true if all the matches are found in the string, not if only one of them is found.

You could try with something like this instead if the filenames only contain one digit. This will fail is there are digits in any other position in the filename.

$srcpath = "C:\Folder\SubFolder3"
$dstpath = "C:\Folder\SubFolder2"
Get-ChildItem -File -Recurse -Path $srcpath |
    ForEach-Object {
        # look for a digit
        if($_.Name -match '[\d]') {
            # is that digit odd?
            if([int]($Matches[0]) % 2 -eq 1) {
                Move-Item -Path $_.FullName -Destination $dstpath
            }
        }
    }

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