【问题标题】:How to maintain a Session info in Powershell script如何在 Powershell 脚本中维护会话信息
【发布时间】:2021-08-27 00:12:17
【问题描述】:

我有如下脚本:

foreach ($var1 in (gc 1.txt)){
 // my code logic
}

这里的 1.txt 文件包含 abc、xyz、pqr 等值的列表, 如果由于任何脚本问题/ctrl+c 停止了脚本,则需要从上次停止的会话重新启动脚本。 要清楚脚本是否已停止在“xyz”处处理文件,并且当我重新启动脚本时,它应该只处理来自“xyz”的逻辑,但不应再次从“abc”重新启动。

请指导我实现这个逻辑。

提前致谢, 帕万·库马尔 D

【问题讨论】:

  • 使用“for”循环并将处理索引保存在文件中。
  • 不需要for-next循环,虽然这是一个选项。

标签: powershell


【解决方案1】:

您需要添加一些计数器并使用索引文件跟踪上次迭代。

然后确保您开始阅读使用select -Skip 中断的文件

<#
.NOTE
    The file index.txt is created at the first run and is used to store 
    the last line accessed of the file to process.

    The index read from index.txt is used to skip by already processed 
    lines at the start of the foreach.

    If the index doesn't need to be stored between session, then use
    a $global.index instead to speed up the script, instead of an index 
    file (or a RAM-drive, not very common any more).

    At each succefull iteration, the index is incremented and then stored in 
    index.txt.

    When starting the stored index.txt is compared with the numbers of 
    lines in the file and will through an error if it's passed End Of File.

    Make sure to **clear** the index.txt before starting the file process 
    fresh.
#>

#initialize counters
[int]$StartLine = Get-Content .\index.txt -ErrorAction SilentlyContinue
if (-not $StartLine){[int]$StartLine = 0} # First run will have no index file
$Index = $StartLine
[int]$LastLineOfFile = (get-content 1.txt).count - 1 # Arrays starts at 0

if ($Index -gt $LastLineOfFile){# Don't start if index passed EOF at last run
    Write-Error "Index passed end of file"
    return
}

foreach ($var in (Get-Content 1.txt | Select -Skip $StartLine)){
    
    "New loop: $Index" | Out-Host # will start empty

    "Processing value: $var" | Out-Host

    ####
    # Processing here
    ####

    "Done processing value: $var" | Out-Host

    $Index++ 
    $Index > index.txt
    "Index incremented" | Out-Host
}

有关使用 RAM 驱动器的好文章,请参阅,即How to Create RAM Disk in Windows 10 for Super-Fast Read and Write Speeds

通过使用 iSCSI 目标服务器,Windows Server 确实(在某种程度上)支持 RAM 磁盘。
看,How to Create a RAM Disk on Windows Server?

【讨论】:

  • 优秀的丹尼斯,它奏效了。谢谢。我们能不能同时保持行文本的比较,这样如果在文本文件中间添加了任何新文本,我们就不会处理它。准确地说,如果行是按顺序排列的,例如:- abc,xyz 等,对于这个给定的逻辑是好的,如果我们在中间添加文本,例如:- abc,ghi,xyz 等,在这个同样,我们不应该处理 abc 和 xyz,而只处理 ghi。请帮我解决一下这个。提前致谢
  • 如果文件在中断后被更改(如果这是问题),那么我建议重新处理整个文件...
  • 是的丹尼斯,但不是重新处理整个文件,我们是否应该比较文本文件中的内容,就像我们在处理完成后写入的返回文件中是否存在“abc”一样,那么它不应该处理并移至下一行。因为我们有包含数百个存储库名称的源文件。例如:通过将 2 个 repo 名称更改为源文件,需要再次从头开始处理那些将再次重复所有 repos 处理的 2 个。您能建议我避免这种情况的最佳方法吗?
  • 也许您可以将已处理的文件标记为完成?通过标记、移动它们还是将完成的文件与索引文件一起保存?
  • 确定 Dennis,会将其标记为解决方案并创建新解决方案。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多