简体   繁体   English

暂停Powershell脚本并继续

[英]Pause a Powershell script and resume

I have a script which currently pulls the file location from a CSV and uploads the files to a database, using a ForEach-Object loop. 我有一个脚本,该脚本当前使用ForEach-Object循环从CSV提取文件位置并将文件上传到数据库。

What I'd like it to do is upload 1000 files, then be able to pause the loop and resume it later from file 1001. 我要执行的操作是上传1000个文件,然后能够暂停循环并稍后从文件1001恢复。

I don't want to use the Start-Sleep command, as I do not want the script to automatically resume after a set amount of time. 我不想使用Start-Sleep命令,因为我不希望脚本在设置的时间后自动恢复。

This is a one time deal, so I'd rather not convert it to a workflow. 这是一次交易,所以我宁愿不将其转换为工作流程。

What command or cmdlet can be used to accomplish this? 可以使用什么命令或cmdlet完成此操作?


The Read-Host command would be perfect if there were a way to break the script and then resume from the same line later. 如果有一种方法可以断开脚本,然后再从同一行继续运行,则“ 读取主机”命令将是完美的选择。

Use pause : 使用pause

For ($i=1; $i -lt 2000; $i++)  {

    if ($i -eq 1001)
    {
         pause
    }
    Write-Host $i
}

Here's how I'd do it: 这是我的处理方式:

$i = 0;
foreach ($file in (Get-ChildItem $path_to_directory)) {
  # Code to upload the file referenced by $file
  if (++$i -eq 1000) {
    Write-Host -NoNewLine '1000 files have been uploaded. Press capital "C" to continue uploading the remaining files...'
    do {
    } until (($Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyUp').Character) -ceq 'C')
  }
}

Using pause , as already suggested in Bluecakes' answer, is a perfectly good solution. 正如Bluecakes的答案中已经建议的那样,使用pause是一个很好的解决方案。 The advantage of this method is that it gives you more control. 这种方法的优点是可以为您提供更多控制。 pause always requires the Enter key and always gives you the same prompt, Press Enter to continue...: , whereas this way you can define both to your liking. 暂停总是需要使用Enter键,并且总是会给您相同的提示, Press Enter to continue...: ,而您可以根据自己的喜好定义两者。

More significantly, and the reason I personally prefer to do it this way in my own scripts, is that you can protect against accidental key presses. 更重要的是,我个人更喜欢在自己的脚本中这样做,原因在于您可以防止意外按键。 In my example I made the required keystroke a capital C, so that it's very unlikely that you'd continue by accident. 在我的示例中,我将必需的按键设置为大写字母C,因此您不太可能会意外继续。

However, if you don't care about any of that and just want a quick and simple say to do it, then pause is really all you need. 但是,如果您对此不关心,只想简单快速地说一遍,那么暂停实际上就是您所需要的。

Something along these lines could work for you... 这些思路可能对您有用...

For ($i=1; $i -lt 50; $i++)  {

    if ($i -eq 10)
    {
        $input = Read-Host "Should I continue Y/N"
        if ($input -eq "N")
        {
           break
        }
    }
    Write-Host $i
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM