我有这个代码:
$u = "JohnDoe" # This user is member of 'Domain users' and 'Test group', so memberOf returns only 'Test group'
$g = $null
if ($u)
{
$g = [array](Get-ADUser -Identity $u -Properties memberOf|select -ExpandProperty memberOf)
}
$g.GetType()
$h = if ($u)
{
[array](Get-ADUser -Identity $u -Properties memberOf|select -ExpandProperty memberOf)
}
else
{
$null
}
$h.GetType()
[array]$i = if ($u)
{
(Get-ADUser -Identity $u -Properties memberOf|select -ExpandProperty memberOf)
}
else
{
$null
}
$i.GetType()
有人可以解释为什么
$g.GetType()
和 $i.GetType()
返回这个(如预期)
:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
以及为什么
h.GetType()
,返回这个(绝对不是预期的)
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
谢谢:)
您的第二个
if
相当于:
$h = if ($u)
{
write-output [array](Get-ADUser -Identity $u -Properties memberOf|select -ExpandProperty memberOf)
# ^^^^^^^^^^^^
}
else
{
$null
}
PowerShell 将项目数组一次一个地“流式传输”(有时称为“展开”)到调用范围 - 因为只返回一项,所以结果是将单个
System.String
项目分配给 $h
。如果结果集中有多个项目,PowerShell 会将它们聚合到一个新的数组对象中,并将 that 分配给 $h
。
这与返回值从函数中流出的方式基本相同:
function x
{
# "bare" values get returned as-is
1
}
write-host ((x).GetType())
# System.Int32
function y
{
# single-item arrays get unrolled and the
# first item returned instead of the array
@( 1 )
}
write-host ((y).GetType())
System.Int32
您的
if
相当于:
function z
{
# multiple-item arrays also get unrolled, but they
# get combined into a *new* array at the receiver
@( 1, 2 )
}
write-host ((z).GetType())
System.Object[]