Reputation: 892
I would like to count how many times that I check the result. This the part of the process looks like:
function GetValueResult
{
...Some Process...
$Result = $ReturnCode
}
GetValueResult
if ($Result -eq 0)
{
Write-Host "The process Pass"
Restart-Computer
}
elseif ($Result -eq 1)
{
Write-Host "Try again"
GetValueResult
#This part I need to know how many times that I call this function "GetValueResult"
}
Anyone can help me how to count how many times that I call the function "GetValueResult"? If it already 3 times, than I need to do further action. Thanks for help.
Upvotes: 0
Views: 290
Reputation: 61013
You could add a simple loop inside your function and output an object with both the ResultCode and the number of tries:
function GetValueResult {
# initialize to error code
$ResultCode = -1
for ($numTries = 0; $numTries -lt 3; $numTries++) {
# ...Some Process...
# exit the loop if we have a correct $ResultCode
if ($ResultCode -eq 0) { break }
Write-Host "Try again"
}
# output an object with the resultcode and the number of tries
[PsCustomObject]@{
ResultCode = $ResultCode
Tries = $numTries + 1
}
}
$result = GetValueResult
if ($result.ResultCode -eq 0) {
Write-Host "The process Pass"
Restart-Computer
}
else {
Write-Host "Bad result after $($result.Tries) tries.."
}
Upvotes: 1
Reputation: 612
You can use increment for this purpose.
$Result = 0
foreach (...){
$Result++
if ($Result -ge 3){
...your action...
}
}
Also, I can't find any loop in your script, so how would you count in this case? Please share more details about what are you trying to achieve with it, perhaps you need to redesign it from the beginning.
Upvotes: 0