萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> PowerShell實現統計函數嵌套深度

PowerShell實現統計函數嵌套深度

   這篇文章主要介紹了PowerShell實現統計函數嵌套深度,本文分享一個函數,可以實現統計腳本執行的嵌套層次,需要的朋友可以參考下

  當你調用某個函數時,PowerShell會增加一次嵌套層次。當一個函數調用了另一個函數,或著腳本,也會增加嵌套層次。今天分享一個函數,它能告訴你的腳本嵌套的層次:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 function Test-NestLevel { $i = 1 $ok = $true do { try { $test = Get-Variable -Name Host -Scope $i } catch { $ok = $false } $i++ } While ($ok)   $i }

  當你調用的函數具有遞歸調用時,上面的函數非常有用,來看一個調用的示例:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 function Test-Diving { param($Depth)   if ($Depth -gt 10) { return }   "Diving deeper to $Depth meters..."   $currentDepth = Test-NestLevel "calculated depth: $currentDepth"   Test-Diving -depth ($Depth+1) }   Test-Diving -depth 1

  當你運行Test-Diving時,函數會調用自己10次。函數使用一個參數來控制嵌套層次,而Test-NestLevel負責返回確切的深度數。

  注意這裡有個區別:Test-NestLevel返回絕對的嵌套層次,參數會紀錄這個函數調用自己多少次。如果Test-Diving被嵌入到另外一個函數中,絕對深度和相對深度會不同。

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 PS C:> Test-Diving -Depth 1 diving deeper to 1 meters... calculated depth: 1 diving deeper to 2 meters... calculated depth: 2 diving deeper to 3 meters... calculated depth: 3 diving deeper to 4 meters... calculated depth: 4 diving deeper to 5 meters... calculated depth: 5 diving deeper to 6 meters... calculated depth: 6 diving deeper to 7 meters... calculated depth: 7 diving deeper to 8 meters... calculated depth: 8 diving deeper to 9 meters... calculated depth: 9 diving deeper to 10 meters... calculated depth: 10   PS C:> & { Test-Diving -Depth 1 } diving deeper to 1 meters... calculated depth: 2 diving deeper to 2 meters... calculated depth: 3 diving deeper to 3 meters... calculated depth: 4 diving deeper to 4 meters... calculated depth: 5 diving deeper to 5 meters... calculated depth: 6 diving deeper to 6 meters... calculated depth: 7 diving deeper to 7 meters... calculated depth: 8 diving deeper to 8 meters... calculated depth: 9 diving deeper to 9 meters... calculated depth: 10 diving deeper to 10 meters... calculated depth: 11   PS C:>

  Test-NestLevel總會返回從當前代碼的作用域到全局作用域的嵌套深度。

copyright © 萬盛學電腦網 all rights reserved