Windows 10 64-bit. PowerShell 5.
How to move files based on file basename using PowerShell gci, foreach, if, -like, move-item and -literalpath
Move 0001_ddmmyy_username[active1]_L_kkkkk.pdf to C:\Users\abc\London
Move 0001_ddmmyy_jacky[active1]_R_kkkkk.pdf to C:\Users\abc\Russia
Move 0001_ddmmyy_jim[active1]_P_kkkkk.pdf to C:\Users\abc\Poland
Change $env:userprofile\desktop. Remove -whatif when you are satisfied it works.
$items = gci -recurse -file *_L_*, *_R_*, *_P_*
foreach($item in $items) {
# Change $env:userprofile\desktop
if($item -like "*_L_*") {
Move-Item -LiteralPath $item "$env:userprofile\desktop\London" -whatif
} elseif($item -like "*_R_*") {
Move-Item -LiteralPath $item "$env:userprofile\desktop\Russia" -whatif
} elseif ($item -like '*_P_*') {
Move-Item -LiteralPath $item "$env:userprofile\desktop\Poland" -whatif
}
}
Comments:
With some cmdlets you will get odd results when you use -Path and any part of the full file name contains []. The fix is to use the -LiteralPath parameter. See Get-Help Move-Item -Parameter *path* – Lee_Dailey
How to move files based on file basename using PowerShell gci, foreach, if, -like, move-item and -literalpath
-Pathand any part of the full file name contains[]. it also happens with some other chars, but those are the only ones i recall. the fix is to use the-LiteralPathparameter instead of the-Pathparameter. you are using the-Pathparameter since you failed to specify anything - and the cmdlets default to-Path. take a look at the output ofGet-Help Move-Item -Parameter *path*.