當(dāng)你調(diào)用某個函數(shù)時,PowerShell會增加一次嵌套層次。當(dāng)一個函數(shù)調(diào)用了另一個函數(shù),或著腳本,也會增加嵌套層次。今天分享一個函數(shù),它能告訴你的腳本嵌套的層次:
function Test-NestLevel { $i = 1 $ok = $true do { try { $test = Get-Variable -Name Host -Scope $i } catch { $ok = $false } $i++ } While ($ok) $i }
當(dāng)你調(diào)用的函數(shù)具有遞歸調(diào)用時,上面的函數(shù)非常有用,來看一個調(diào)用的示例:
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
當(dāng)你運(yùn)行Test-Diving時,函數(shù)會調(diào)用自己10次。函數(shù)使用一個參數(shù)來控制嵌套層次,而Test-NestLevel負(fù)責(zé)返回確切的深度數(shù)。
注意這里有個區(qū)別:Test-NestLevel返回絕對的嵌套層次,參數(shù)會紀(jì)錄這個函數(shù)調(diào)用自己多少次。如果Test-Diving被嵌入到另外一個函數(shù)中,絕對深度和相對深度會不同。
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總會返回從當(dāng)前代碼的作用域到全局作用域的嵌套深度。
標(biāo)簽:鶴崗 德州 六盤水 運(yùn)城 湛江 山南 濟(jì)南 岳陽
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PowerShell實(shí)現(xiàn)統(tǒng)計(jì)函數(shù)嵌套深度》,本文關(guān)鍵詞 PowerShell,實(shí)現(xiàn),統(tǒng)計(jì),函數(shù),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。