小编Kas*_*urg的帖子

添加输出流时,布尔函数会更改返回的数据类型

我在理解 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
Run Code Online (Sandbox Code Playgroud)

powershell

2
推荐指数
1
解决办法
701
查看次数

标签 统计

powershell ×1