troubleshooting Question

Needing help with a IF in a WHILE Loop

Avatar of Robert Lem
Robert Lem asked on
2 Comments1 Solution75 ViewsLast Modified:
I am very new to PowerShell -- not the same as bash for sure. This might be very simple to resolve for someone who is familiar with PowerShell. The purpose of this script is to move incoming files from a shared folder "MYincoming" to a non-shared folder "MYfiles." It's in a loop, but I am running into a problem with the loop. When I start the script it will pick up the right condition, meaning "Source contains files" if there are files in the incoming folder. If none, it will pick up the next condition "Source does not contain files." However, once it picks up one of the two conditions it won't change or check the next condition.

I place files in the incoming folder and it picks them up and move them to the "MYfiles," then sleep and continue to output "Source contains Files" every 30 seconds. I expected it change to "Source does not contain files" once the files have moved, but it a bit loopy at that point. I am not sure how to resolve this. I would appreciate any guidance, even if it shows how little I know about PowerShell. You would be right, it's the first time I try PowerShell.

See script here:

$Source = "f:\MYincoming"
$Destination = "f:\MYfiles"
$Date = Get-Date -format M
$LogFile = "f:\MYfiles\Logs\$Date-xfer_log.txt"

# Get existing files into arrays:
$SourceFiles = Get-ChildItem -Path $Source -Recurse

# Loop all files in the source folder:

while(1) {
if($SourceFiles.Count) {

    "Source contains files"
    Get-Date | Out-File $LogFile -Append
         $SourceFiles | ForEach-Object {
              $FilePath = $_.fullname
          if (Test-Path -Path $_.fullname)
              Move-Item $FilePath -Destination $destination -force
              $FilePath | Out-File $LogFile -Append
else {
    "Source does not contain files"  
start-sleep -s 30

Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros