簡體   English   中英

添加輸出流時,布爾函數會更改返回的數據類型

[英]Boolean function changes returned datatype when output streams are added

我在理解 powershell 的內部工作原理時遇到了一些麻煩。 以這個例子為例。 我有一個布爾函數 (Test-MyCode),只要省略了 Write-Output cmdlet,它就可以正常工作。 添加 Write-Output cmdlet 后,返回類型將更改為 Object[] 數組。

.GetType() 可用於查看數據類型。

為什么是這樣?

function Test-MyCode
{
    if( 2 -gt 0)
    {
        Write-Output "This function will return false"
        return $false
    }
    else
    {
        Write-Output "could return true if condition is changed"
        return $true
    }
}

function Invoke-MyCode
{
    Write-Output "this is main"
    Write-Output "do stuff"
    # Test-MyCode is configured to return false... yet its true
    if (Test-MyCode)
    {
        Write-Output "yep, no longer boolean"
    }

}

Invoke-MyCode

Get-Help Write-Output

NAME
    Write-Output

SYNOPSIS
    Sends the specified objects to the next command in the pipeline. If the
    command is the last command in the pipeline, the objects are displayed in
    the console.

我認為您的主要困惑源於這樣一個事實,即PowerShell 函數沒有靜態綁定到返回某種類型

return關鍵字的工作方式與C# ,但大致意味着:

  1. return關鍵字后的表達式結果調用Write-Ouput
  2. 退出當前作用域

有關更多信息,請參閱about_Returnabout_Functionsabout_Functions_OutputTypeAttribute幫助文件


在上面的簡單示例中,我會被創建一個包含字符串和結果的新自定義對象所吸引,但此“解決方案”的適用性可能會有所不同:

function Test-MyCode
{
    if( 2 -gt 0)
    {
        New-Object psobject -Property @{
            Message = "This function will return false"
            Result  = $false
        }
    }
    else
    {
        New-Object psobject -Property @{
            Message = "could return true if condition is changed"
            Result  = $true
        }
    }
}

function Invoke-MyCode
{
    Write-Host "this is main"
    Write-Host "do stuff"
    # Test-MyCode is configured to return false... yet its true
    if (($codetest = Test-MyCode).Result)
    {
        Write-Host $codetest.Message
    }
}

Invoke-MyCode

通知怎么Write-Output是隱含的時候我只是“垃圾”的對象到與管道New-Object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM