i have the following batch file set to move files periodically from one folder to another, but i noticed that if folder was empty and the batch script runs it actually move the folder itself.
So i want to check if folder is empty stop processing to prevent folder deletion else continue with script
@echo off
for /f %%a in ('powershell -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set
datetime=%%a
echo copying file
move C:\Shares\FTP\*.*
C:\Shares\FTPBackup\%datetime%".csv
echo done
It is easier to do this all in PowerShell. This requires the current Windows PowerShell 5.1+ or PowerShell Core. When you are confident that the correct directory will be created and the correct files moved, remove the -WhatIf
from the New-Item
and Move-Item
commands.
$Files = Get-ChildItem -File -Path 'C:\Shares\FTP'
if ($Files.Count -gt 0) {
$NewDir = 'C:\Shares\FTPBackup\$(Get-Date -format "yyyy_MM_dd__HH_mm_ss")'
if (-not (Test-Path -Path $NewDir)) { New-Item -ItemType 'Directory' -Path $NewDir -WhatIf | Out-Null }
foreach ($File in $Files) {
Move-Item -Path $File.FullName -Destination $NewDir -WhatIf
}
}
If you are dead set committed to doing it as a cmd.exe script, something like this might work.
powershell.exe -NoLogo -NoProfile -Command ^
"$Files = Get-ChildItem -File -Path 'C:\Shares\FTP';" ^
"if ($Files.Count -gt 0) {" ^
"$NewDir = 'C:\Shares\FTPBackup\$(Get-Date -format "yyyy_MM_dd__HH_mm_ss")';" ^
"if (-not (Test-Path -Path $NewDir)) { New-Item -ItemType 'Directory' -Path $NewDir -WhatIf | Out-Null };" ^
"foreach ($File in $Files) {" ^
"Move-Item -Path $File.FullName -Destination $NewDir -WhatIf" ^
"}" ^
"}"