azurepowershellazure-powershell

Powershell if function calling another function


I have 2 functions when I call the second function from the first one, always returns true doesn't matter if the second function has false return:

function IsPodRunning($podName) {
  Write-Output "IsPodRunning $podName"
  return $false;
}

function WaitForPodStart($podName) {
  While ($true) {
    If (IsPodRunning -podName $podName) {
      Write-Output "WaitForPodStart IsPodRunning"
      Break
    }else {
      Write-Output "WaitForPodStart IsNotPodRunning"
    }
    Start-Sleep -Milliseconds 100
  }
}

The second function works as expected if I call directly but not through another function. IsPodRunning -podName "podName1" Works as expected

WaitForPodStart -podName "podName1" doesn't call second function

After making a bunch of tests I found the issue could be the if statement of the first function, but not sure what I'm doing wrong.


Solution

  • There are few reasons for this PowerShell function conflict behavior to verify. Check below to resolve the issue.

    To avoid issues with function return values, use Write-Host instead of Write-Output for printing outputs to the console. Write-Host writes directly to the console, whereas Write-Output sends output to the pipeline, which can be interpreted as part of a function's return value.

    Reference SO for the relevant information on difference between them.

    function IsPodRunning($podName) {
      Write-Host "IsPodRunning $podName"
      return $false;
    }
    

    enter image description here

    Alternatively, you can also remove return statement from the PowerShell function and modify the code as shown below.

    function IsPodRunning($podName) {
      Write-Host "IsPodRunning $podName"
      $false;
    }
    

    And also check if statement is properly given under the WaitForPodStart :

    If ($(IsPodRunning -podName $podName))

    After modifying it, try checking the pod running status as shown below and it worked as expected for me.

    enter image description here