[英]ForEach-Object in Pipeline Not Working
Could someone explain to me why the following works 有人可以向我解释以下原因的原因
$Users = 'First1 Last1','First2 Last2','First3 Last3'
foreach ($User in $Users)
{
(Get-ADUser -Filter *).Where{$_.Name -like "*$User*"}
}
but this does not 但这不是
$Users | % { (Get-ADUser -Filter *).Where{$_.Name -like "*$_*"} }
I feel like it's essentially the exact same thing but the first commands return data while the second does not 我觉得这基本上是完全相同的东西,但是第一个命令返回数据,而第二个则不
It's not the same thing, because .Where{$_.Name -like "*$_*"}
uses the current object variable twice. 这是不一样的,因为
.Where{$_.Name -like "*$_*"}
使用当前对象变量两次。 In $_.Name
it should refer to the current object from Get-ADUser
, whereas in "*$_*"
it should refer to the current string from $Users
, but actually also refers to the current object from Get-ADUser
. 在
$_.Name
Get-ADUser
,它应引用Get-ADUser
的当前对象,而在"*$_*"
它应引用$Users
的当前字符串,但实际上也应引用Get-ADUser
的当前对象。
Something like this would make the two statements the same: 这样的事情会使两个语句相同:
$Users | % { $u = $_; (Get-ADUser -Filter *).Where{$_.Name -like "*$u*"} }
In the second loop variable $_
starts being the first user of $Users
array, but it is overridden by the output of Get-ADUser
. 在第二个循环中,变量
$_
开始成为$Users
数组的第一个用户,但被Get-ADUser
的输出覆盖。
In other words in the second loop in {$_.Name -like "*$_*"}
the *$_*
you think it is equivalent to $User
it is not. 换句话说,在
{$_.Name -like "*$_*"}
的第二个循环中,您认为*$_*
等效于$User
而不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.