I have a code:
cls
$folderPath = 'Y:\lit\Retail\abc\abc\FTP-FromClient\AMS\2022-03-23'
$files = Get-ChildItem $folderPath
$destination='Y:\lit\Retail\abc\abc\FTP-FromClient\AMS\2022-03-23\bz2'
$leftfiles=('20220322054419',
'20220322083959',
'20220322084715',
'20220322085207',
'20220322085250',
'20220322085858',
'20220322090236',
'20220322090410',
'20220322090450'
'20220322170306')
foreach($j in $leftfiles)
{
foreach($f in $files)
{
if ($f -contains $j)
{
Move-Item $f.FullName $destination
}
}
}
In this $folderPath I have some files:
$folderPath = 'Y:\lit\Retail\abc\abc\FTP-FromClient\AMS\2022-03-23'
File naming has some naming convention as which matches with the numbers inside the aray:
Colly_20220322054419.dat.bz2
Colly_1_20220322084715.dat.bz2
Colly_3_20220322085207.dat
I only need to move all the files to the destination
,if filename contains the number inside array elements. So I tried using -contains
to move the file but it's not working:
foreach($j in $leftfiles)
{
foreach($f in $files)
{
if ($f -contains $j)
{
Move-Item $f.FullName $destination
}
}
}
CodePudding user response:
Your code could be simplified if you use a Where-Object
clause that filters the files to move using the regex -match
operator
$folderPath = 'Y:\lit\Retail\abc\abc\FTP-FromClient\AMS\2022-03-23'
$destination = 'Y:\lit\Retail\abc\abc\FTP-FromClient\AMS\2022-03-23\bz2'
$leftfiles = '20220322054419', '20220322083959','20220322084715','20220322085207','20220322085250',
'20220322085858','20220322090236','20220322090410','20220322090450','20220322170306'
# first make sure the destination folder exists
$null = New-Item -Path $destination -ItemType Directory -Force
# join the items from $leftfiles with a pipe symbol (=the regex 'OR')
$regex = $leftfiles -join '|'
Get-ChildItem -Path $folderPath -File |
Where-Object { $_.BaseName -match $regex } |
Move-Item -Destination $destination
If you want to test this out first, append switch -WhatIf
to the Move-Item
line. THat way, nothing actually gets moved. Only in the console, it is displayed what would be moved