在 PowerShell 中的計數器

在程式設計中,計數器用於跟踪在您的程式中需要計數的內容。通常,這是一個數字型別的變量,初始化為 0
。
有幾種方法可以在程式中增加計數器的值。在本文中,我們將專注於在 PowerShell 中實現計數器的不同方法。
PowerShell 中的基本計數器
實現計數器的基本方法是聲明一個變量並將其初始化為 0
,如下所示。
$counter = 0
讓我們將 $counter
變量的值打印到 PowerShell 命令窗口。
Write-Host $counter
輸出:
我們可以使用兩種方法來增加 $counter
變量的值。一種傳統的方法是將 1 加到 $counter
,並將結果重新賦值給 $counter
。
$counter = $counter + 1
輸出:
另一種方法是使用遞增(++
)運算符。
$counter++
輸出:
接下來,我們將使用後遞增來增加 $countVar
的值。
$counterHolder = $countVar++
Write-Host $counterHolder
輸出:
正如您所看到的,$counterHolder
變量的值為 0
,這意味著 $countVar++
在該表達式中沒有遞增。但實際上,$countVar
的值應該已經被遞增。讓我們打印 $countVar
變量的值。
PowerShell 中的前遞增運算符
前遞增運算符用於在將變量用於表達式之前增加變量的值。讓我們通過以下例子來理解這一點。
首先,我們將聲明一個名為 $preIncrVar
的變量並初始化為 0
。
$preIncrVar = 0
Write-Host $preIncrVar
讓我們按照如下方式使用前遞增運算符。
$preIncrVarHolder = ++$preIncrVar
Write-Host $preIncrVarHolder
輸出:
如預期的那樣,$preIncrVarHolder
變量的值為 1
,這表示前遞增運算符在使用的表達式中增加了 $preIncrVar
變量的值。這些方法可以在 PowerShell 中的 for
、while
及 do...while
循環中使用。
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.