0

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.

1
  • 1
    I guess you missing some details as I suspect that the counter needs to survive a Restart-Computer in which case I would use the registry for keeping track of your counter. In which case it is also good to know if it conserns the SYSTEM account or not. Commented Dec 3, 2020 at 7:46

2 Answers 2

1

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.."
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.