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
}
}
CodePudding user response:
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
}
}
}