0

I need help in writing one PS script to move files at regular intervals from one folder to the another for processing. I have used the below mentioned code but I am not getting on how to check whether the file is already present in the destination or not. It it is present then the file shouldn't be copied. Please help.

$destination = "C:\Users\User\Desktop\Destination\"
$source = "C:\Users\User\Desktop\Source"
$files = Get-ChildItem $source
Write-Host $files
foreach($file in $files)
{

    $path = "C:\Users\User\Desktop\Source\" + $file
    Move-Item -Path $path -Destination $destination -Force
}

Please help on Checking whether the file is there in Destination folder and skip it from moving.

Regards,

Mitesh Agrawal

Mitesh Agrawal
  • 67
  • 3
  • 12
  • Does this answer your question? [Check if a file exists or not in Windows PowerShell?](https://stackoverflow.com/questions/31879814/check-if-a-file-exists-or-not-in-windows-powershell) – RoadRunner Mar 30 '20 at 06:31
  • 1
    Not sure if this is a duplicate, but it seems you can just use `Test-Path` to ensure the file doesn't exist before moving. Something like `if (-not(Test-Path -Path $path)){ Move-Item -Path $path -Destination $destination}`. – RoadRunner Mar 30 '20 at 06:41
  • This might be easier with robocopy – Andy Mar 30 '20 at 11:08

2 Answers2

2

Using Tes-Path with leaf property will check if any file is exist or not.

if !(Test-Path $path -PathType leaf) { Move-Item -Path $path -Destination $destination -Force }

Kamel
  • 47
  • 4
0

Thanks @kamel. The below code worked perfectly.

$destination = "C:\Users\User1\Desktop\Destination\"
$source = "C:\Users\User1\Desktop\Source"
$files = Get-ChildItem $source
Write-Host $files
foreach($file in $files)
{
    $path1 = "C:\Users\User1\Desktop\Source\" + $file
    $path2 = "C:\Users\User1\Desktop\Destination\" + $file
    if (!(Test-Path $path2 -PathType leaf)) 
    { 
    Move-Item -Path $path1 -Destination $destination -Force
    }
}
Mitesh Agrawal
  • 67
  • 3
  • 12