Powershell if 函数调用另一个函数

问题描述 投票:0回答:1

当我从第一个函数调用第二个函数时,我有两个函数,总是返回

true
,如果第二个函数有
false
返回也没关系:

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
  }
}

如果我直接调用而不是通过另一个函数调用,第二个函数将按预期工作。

IsPodRunning -podName "podName1"
按预期工作

WaitForPodStart -podName "podName1"
不调用第二个函数

经过一系列测试后,我发现问题可能是第一个函数的 if 语句,但不确定我做错了什么。

azure powershell azure-powershell
1个回答
0
投票

此 PowerShell 函数冲突行为的原因很少需要验证。请检查以下内容以解决问题。

为了避免函数返回值出现问题,请使用

Write-Host
而不是
Write-Output
将输出打印到控制台。
Write-Host
直接写入控制台,而
Write-Output
将输出发送到管道,可以将其解释为函数返回值的一部分。

参考SO了解它们之间差异的相关信息。

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

enter image description here

或者,您也可以从 PowerShell 函数中删除

return
语句并修改代码,如下所示。

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

并检查是否在

WaitForPodStart
下正确给出了声明:

If ($(IsPodRunning -podName $podName))

修改后,尝试检查 pod 运行状态,如下所示,它对我来说符合预期。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.