[英]Boolean function changes returned datatype when output streams are added
I'm having some trouble understanding the inner workings on powershell.我在理解 powershell 的内部工作原理时遇到了一些麻烦。 Take this example.
以这个例子为例。 I have a boolean function (Test-MyCode), that works fine, as long as the Write-Output cmdlet is left out.
我有一个布尔函数 (Test-MyCode),只要省略了 Write-Output cmdlet,它就可以正常工作。 Once the Write-Output cmdlet is added, the return type changes to a Object[] array.
添加 Write-Output cmdlet 后,返回类型将更改为 Object[] 数组。
.GetType() can be used to view the datatype. .GetType() 可用于查看数据类型。
Why is this?为什么是这样?
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
From Get-Help Write-Output
:从
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.
I think your main confusion stems from the fact that PowerShell functions are not statically bound to return a certain type .我认为您的主要困惑源于这样一个事实,即PowerShell 函数没有静态绑定到返回某种类型。
The return
keyword doesn't work exactly like in C#
, but roughly means: return
关键字的工作方式与C#
,但大致意味着:
Write-Ouput
on the results of the expression after the return
keywordreturn
关键字后的表达式结果调用Write-Ouput
See theabout_Return
,about_Functions
andabout_Functions_OutputTypeAttribute
help files for more information有关更多信息,请参阅
about_Return
、about_Functions
和about_Functions_OutputTypeAttribute
帮助文件
In the simple example above, I would be attracted to creating a new custom object that contains both the string and the result, but the applicability of this "solution" may vary:在上面的简单示例中,我会被创建一个包含字符串和结果的新自定义对象所吸引,但此“解决方案”的适用性可能会有所不同:
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
Notice how Write-Output
is implied when I just "dump" an object onto the pipeline with New-Object
通知怎么
Write-Output
是隐含的时候我只是“垃圾”的对象到与管道New-Object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.