Gwill Zx Spectrum
Gwill Zx Spectrum

Reputation: 11

Check if file exist then continue with the code in Powershell

I need to check if some pdf exists in c:\pdf and if exists continue with the execution, if not, check again every 15th second.

My actual code just checks for files in the folder and print if there is something, if not just repeat again and again. My problem is that sometimes my code deletes the items before printing, thats why I want to loop in the file check and only continue with my code, if a file exists.

My code:

Do {
    $fileDirectory = "C:\pdf";
    foreach($file in Get-ChildItem $fileDirectory)
    {
        $filePath = $fileDirectory + "\" + $file;
        Start-Process –FilePath $filePath –Verb Print -WindowStyle Minimized -PassThru
    }
    Start-Sleep -s 2
    Remove-Item c:\pdf\* -recurse
    Get-Process AcroRd32 | % { $_.CloseMainWindow() }
    sleep 15
} while ($true)

Upvotes: 1

Views: 13802

Answers (1)

Avshalom
Avshalom

Reputation: 8889

You can just use simple while block:

While (!(Test-Path C:\pdf\file.pdf -ErrorAction SilentlyContinue))
{
  # endless loop, when the file will be there, it will continue
}

# Next code block here #

Upvotes: 2

Related Questions