简体   繁体   English

根据文件名中的奇数移动文件 - powershell

[英]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.我试过使用 if 语句和 for 循环无济于事。 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.我相信-match运算符仅在字符串中找到所有匹配项时才返回 true,如果仅找到其中一个匹配项则不会。

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.如果文件名中的任何其他 position 中有数字,这将失败。

$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
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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