Hi everybody
Firstly, thank you so much for you help recently. But I have a new problem, still on the same script. I would like to to move file for a directory to a new directory, but when I use Move-Item -Force, if file already exist Powershell keep older File. I’ve found a script with a function that keep newerf file but that doesn’t work. Here my complete script :
$path = 'C:\Users\margu\Desktop\Test_Copy\*'
$destinationFolder = 'C:\Users\margu\Desktop\Test_Paste\'
$fileList = Get-ChildItem -Path $path -Include tes* -File -Recurse
$hour10 = (Get-Date 10:00).ToString("HH:mm")
# If file already exist, keep newer
function ShouldMove
{
param($File, $Destination)
$testPath = Join-Path $Destination -ChildPath $File.Name
if(Test-Path $testPath)
{
# If the destination folder contains this file name
$destFile = Get-Item $testPath
if($File.CreationTime -gt $destFile.CreationTime)
{
# If the source file is newer return `$true`
return $true
}
# Else `$false`
return $false
}
# If destination does not have this file, return `$true`
$true
}
# Test if folder exist
if (!(Test-Path $destinationFolder))
{
New-Item -Path $destinationFolder -ItemType Directory
}
# Move Files
foreach ($file in $fileList)
{
$dateFile = (Get-Item -Path $file).LastWriteTime
$hourFile = $dateFile.ToString("HH:mm")
# Set name according next day or current day
if ($hourFile -ge $hour10)
{
$name = ($file.LastWriteTime.AddDays(1).ToString('ddMMyyyy')) + $file.Extension
}
else
{
$name = ($file.LastWriteTime.ToString('ddMMyyyy')) + $file.Extension
}
$destinationFile = Join-Path -Path $destinationFolder -ChildPath $name
if(-not $destinationFile) { continue }
if(ShouldMove -File $file -Destination $destinationFile)
{
# `-Force` to replace it
Move-Item -LiteralPath $file.FullName -Destination $destinationFile -Force
continue
}
# If `ShouldMove` returned `$false` then, instead of moving the file, delete the source
Remove-Item -LiteralPath $destinationFile.FullName
}
So how can I keep the newer file in new directory with this script.
Thank you for your help and have a good day