【问题标题】:Check if file exist then continue with the code in Powershell检查文件是否存在,然后继续使用 Powershell 中的代码
【发布时间】:2018-06-21 22:25:56
【问题描述】:

我需要检查 c:\pdf 中是否存在某些 pdf,如果存在则继续执行,如果不存在,则每 15 秒再检查一次。

我的实际代码只是检查文件夹中的文件并打印是否有东西,如果不是一次又一次地重复。我的问题是,有时我的代码会在打印之前删除项目,这就是为什么我想循环检查文件并仅在文件存在时继续执行我的代码。

我的代码:

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)

【问题讨论】:

  • 您不应该在删除之前处理​​所有文件,在此期间可以添加更多文件,您应该一次处理并删除它们,以帮助减少这种竞争条件导致您丢失未处理的文件。
  • 我删除了标签pdf,因为您的问题不是关于 PDF 文件。您可以对任何其他文件扩展名提出同样的问题。

标签: file powershell loops exists


【解决方案1】:

你可以使用简单的 while 块:

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

# Next code block here #

【讨论】:

  • 这适用于我的代码,非常感谢。我只是尝试使用我的代码,代码只打印一个 pdf,如果我放置多个 pdf,则脚本忽略其他的。我现在的代码: Do { While (!(Test-Path C:\pdf*.pdf -ErrorAction SilentlyContinue)) { # 无限循环,当文件存在时,它将继续 } #my code } while ($true )
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 2015-02-21
  • 2011-12-22
  • 1970-01-01
相关资源
最近更新 更多