繁体   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