GUI中的Powershell写入进度命令在完成之前立即停止



我使用的代码在独立环境中运行得很好,但现在我把它放进了一个按钮,它就停止了。例如,我有400571行,我在其中查找匹配项,进度条停在400000行,因为我告诉他每1000行更新一次写入进度以提高性能。

我很确定关键点必须是if($i%1000-eq 0(,因为如果我把它降到10,他会停在400570,仍然不会罚分,但我不想把它设置为1,因为每行刷新进度条都需要更多的时间。

按钮中包含的代码为:

$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(30,10)
$OKButton.Size = New-Object System.Drawing.Size(300,92)
$OKButton.Text = "Filtern"
$OKButton.Name = "Filter"
$OKButton.DialogResult = [System.Windows.Forms.DialogResult]::None
$OKButton.Add_Click({$i= 0
$path = "C:tempsmtpfilterLNS5filter.txt"
$length = (Get-Content $path).Length
#Datum, Hostname und Message Nummer
$result = Get-Content $path | ForEach-Object {
if($_ -match '(d{2}.d{2}.d{4} d{2}:d{2}:d{2}).*(((?:d{1,3}.){3}d{1,3})) disconnected.?s+(d+) message[s]'){
try {
#$dns = [System.Net.Dns]::GetHostEntry($matches[2]).HostName
}
catch { 
#$dns = 'Not available' 
}
[PsCustomObject]@{
IP       = $matches[2]
Messages = [int]$matches[3]
#DNSName  = $dns
Date     = [datetime]::ParseExact($matches[1], 'dd.MM.yyyy HH:mm:ss', $null)
}
$i++
if($i % 1000 -eq 0){
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length)  * 100)
}
}}
#Messages Counted
$cumulative = $result | Group-Object -Property IP | ForEach-Object {
[PsCustomObject]@{
IP = $_.Name
Messages = ($_.Group | Measure-Object -Property Messages -Sum).Sum
#DNSName = $_.Group[0].DNSName
Date    = ($_.Group | Sort-Object Date)[-1].Date
}
}})
$objForm.Controls.Add($OKButton)

(我#dns命令,因为我现在远程工作,解析名称需要很长时间(

您的foreach-object运行了400571次-您只需在迭代400000时停止更新进度条。

如果你在foreach对象完成后再次更新进度条,你将达到魔法100%完成。。。

$result = Get-Content $path | ForEach-Object {
...
}}
# final update to progress bar with total items processed
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length)  * 100)
#Messages Counted
$cumulative = ...

更新

您还需要将计数器逻辑移到if子句之外,否则您只计算处理的匹配记录的数量。。。

$result = Get-Content $path | ForEach-Object {
if($_ -match '(d{2}.d{2}.d{4} d{2}:d{2}:d{2}).*(((?:d{1,3}.){3}d{1,3})) disconnected.?s+(d+) message[s]'){
...
# move these lines out from the "if( $_ -match ..."
$i++
if($i % 1000 -eq 0)
{
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length)  * 100)
}
}
}

成为

$result = Get-Content $path | ForEach-Object {
if($_ -match '(d{2}.d{2}.d{4} d{2}:d{2}:d{2}).*(((?:d{1,3}.){3}d{1,3})) disconnected.?s+(d+) message[s]')
{
...
}
# now we're counting *every* record, not just the ones that match
$i++
if( $i % 1000 -eq 0 )
{
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length)  * 100)
}
}
# final update to progress bar with total items processed
Write-Progress -activity "Searching for matches" -status "Scanned: $i of $($length)" -percentComplete (($i / $length)  * 100)
...

最新更新