使用自定義Powershell函數將返回所有函數輸出。我試圖通過編寫一個只返回$ true或$ false的包裝函數來消除這種限制/混淆。Powershell - 動態函數調用
但是,我正在努力與動態函數調用。 。 。專門傳遞參數。
請注意函數名稱和函數參數都傳遞給「ExecBoolean」。
代碼示例:
# Simplifies calls to boolean functions in Powershells scripts
# Helps solve this problem -> http://www.vistax64.com/powershell/107328-how-does-return-work-powershell-functions.html
function Foo([string]$sTest, [int] $iTest)
{
Write-Host "sTest [" $sTest "]."
Write-Host "iTest [" $iTest "]."
if ($iTest -eq 1)
{
return $true
}
else
{
return $false
}
}
function ExecBoolean ([string] $sFunctionName, [array] $oArgs)
{
Write-Host "Array Length = " $oArgs.Length ", Items = [" $oArgs[0..($oArgs.Length - 1)] "]"
$oResult = & $sFunctionName $oArgs[0..($oArgs.Length - 1)]
# Powershell returns all function output in oResult, just get the last item in the array, if necessary.
if ($oResult.Length -gt 0)
{
return $oResult[$oResult.Length - 1]
}
else
{
return $oResult
}
}
$oResult = ExecBoolean "Foo" "String1", 1
Write-Host "Result = " $oResult
電流輸出:
Array Length = 2 , Items = [ String1 1 ]
sTest [ String1 1 ].
iTest [ 0 ].
Result = False
所需的輸出:
Array Length = 2 , Items = [ String1 1 ]
sTest [ String1 ].
iTest [ 1 ].
Result = True
在PowerShell中v1.0是這可能嗎?
謝謝。
謝謝,是的,我明白髮生了什麼事。我認爲/希望$ oArgs [0 ..($ oArgs.Length - 1)]不會被視爲一個數組,而是一個參數列表0,1,2等。 我知道「out-null 「技巧,但我試圖避免當開發人員忘記使用它或只是不知道哪些語句返回輸出時出現的問題。 – MattH 2010-02-15 23:49:28