为什么使用基于括号的-Filter参数时$ PSItem的行为不符合预期? [英] Why doesn't $PSItem behave as expected when using a bracket-based -Filter argument?

查看:95
本文介绍了为什么使用基于括号的-Filter参数时$ PSItem的行为不符合预期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在帮助用户解决此问题,并链接到我的答案:使用Powershell脚本仅使用电子邮件地址即可将用户从.csv添加到A / D组吗?

I was assisting a user with this question, linked to my answer here: Powershell script to add users to A/D group from .csv using email address only?

最初,我为 Get-AdUser 使用基于括号的过滤器编写脚本,如下所示:

Initially I wrote the script as follows, using a bracket-based filter for Get-AdUser like follows:

Import-CSV "C:\users\Balbahagw\desktop\test1.csv" | 
  Foreach-Object {

    # Here, $_.EmailAddress refused to resolve
    $aduser = Get-ADUser -Filter { EmailAddress -eq $_.EmailAddress }

    if( $aduser ) {
      Write-Output "Adding user $($aduser.SamAccountName) to groupname"
      Add-ADGroupMember -Identity groupname -Members $aduser
    } else {
      Write-Warning "Could not find user in AD with email address $($_.EmailAddress)"
    }
  }

但是, $ _。EmailAddress 无法填充值。但是,将 Get-ADUser 过滤器更改为基于字符串的过滤器可按预期工作:

However, $_.EmailAddress failed to populate a value. However, changing the Get-ADUser filter to a string-based filter worked as intended:

$ aduser = Get-ADUser -Filter EmailAddress -eq'$($ _。EmailAddress)'

有什么奇怪的地方我正在体验,为什么?是因为当我使用方括号时,它被视为新作用域,而 $ PSItem 将不会跟随?

What is the strangeness I'm experiencing, and why? Is it because when I'm using brackets, it's treated as a new scope and the $PSItem won't follow?

推荐答案


  • -Filter 参数通常是 string 参数(使用

    Get-Help Get-AdUser-参数过滤器进行验证

    • -Filter parameters are generally string parameters (verify with
      Get-Help Get-AdUser -Parameter Filter)


      • 它们通常接受 PowerShell代码-过滤器是提供商特定的,并且通常具有自己的语法,尽管碰巧对于AD cmdlet,应为PowerShell- 类似

        而且,它们通常不了解PowerShell 变量(如下所示)。

      • They generally do not accept PowerShell code - filters are provider-specific and often have their own syntax, although it happens to be PowerShell-like in the case of the AD cmdlets.
        Also, they generally have no knowledge of PowerShell variables (see below).

      因此,当 script块 {...} )传递,它被转换为字符串,该字符串求值为其 literal 的内容(开头 {和结尾的} ):

      Thus, when a script block ({ ... }) is passed, it is converted to a string, which evaluates to its literal contents (everything between the opening { and the closing }):


      • {EmailAddress -eq $ _。EmailAddress } .ToString()产生文字字符串 EmailAddress -eq $ _。EmailAddress -没有任何评估-这就是 Get-AdUser 看到-没有评估。

      • { EmailAddress -eq $_.EmailAddress }.ToString() yields the literal string EmailAddress -eq $_.EmailAddress - without any evaluation - and that's what Get-AdUser sees - no evaluation takes place.

      以一种善意的方式却被误导了努力支持将脚本块传递到AD cmdlet的 -Filter 参数的广泛但不明智的做法,看来这些cmdlet实际上显式扩展了 simple 变量引用,例如它们收到的字符串文字中的 $ _ ,但这不适用于表达式,例如访问<变量( $ _。EmailAddress )的em>属性

      In a presumably well-meaning but misguided effort to support the widespread, but ill-advised practice of passing script blocks to the -Filter parameter of AD cmdlets, it seems that these cmdlets actually explicitly expand simple variable references such as $_ in the string literal they receive, but that doesn't work with expressions, such as accessing a property of a variable ($_.EmailAddress)

      因此, -Filter 参数通常应作为可扩展字符串 ... ;在当前情况下:

      Therefore, -Filter arguments should generally be passed as expandable strings ("..."); in the case at hand:

       -Filter  "EmailAddress -eq '$($_.EmailAddress)'"
      

      也就是说,唯一可靠的解决方案是将 strings 与可变部分一起使用

      That is, the only robust solution is to use strings with the variable parts baked in, up front, via string expansion, as shown above.

      适用于既不是数字也不是数字的值字符串,例如 dates ,您可能必须使用 literal 字符串('...')并依靠AD提供程序评估对PowerShell变量的简单引用(例如 $ date 的能力的说明-请参阅我的答案以获取详细信息。

      For values that are neither numbers nor strings, such as dates, you may have to use a literal string ('...') and rely on the AD provider's ability to evaluate simple references to PowerShell variables (e.g., $date) - see this answer of mine for details.

      如上所述,AD过滤器的语法仅类似于PowerShell- like :它仅支持PowerShell支持的一部分运算符,并且所支持的运算符的行为也有所不同-请参见 Get_Help about_ActiveDirectory_Filter

      As stated, the syntax of AD filters is only PowerShell-like: it supports only a subset of the operators that PowerShell supports and those that are supported differ subtly in behavior - see Get-Help about_ActiveDirectory_Filter.


      • 使用脚本块是诱人的,因为其中的代码不需要转义嵌入的引号/不需要交替使用引号字符,也不需要使用子表达式运算符 $(...)。但是,除了使用脚本块作为字符串通常效率不高外,这里的问题是脚本块承诺不能保留:它看起来像您一样重新传递了一段 PowerShell 代码,但事实并非如此-它仅在简单情况下才起作用(然后仅由于上述错误的调整而起作用);通常,很难记住它在什么情况下不起作用,如果失败了怎么办。

      • It is tempting to use script blocks, because the code inside requires no escaping of embedded quotes / no alternating of quote chars and no use of subexpression operator $(...). However, aside from using script blocks as strings being inefficient in general, the problem here is that the script block is making a promise that it cannot keep: it looks like you're passing a piece of PowerShell code, but you're not - and it works only in simple cases (and then only due to the misguided accommodation mentioned above); generally, it's hard to remember under what circumstances it doesn't work and how to make it work if it fails.

      它因此,很遗憾官方文档的示例中使用了脚本块。

      It is therefore really unfortunate that the official documentation uses script blocks in its examples.

      有关更全面的讨论,请参见< a href = https://stackoverflow.com/a/44184818/45375>我的答案。

      For a more comprehensive discussion, see this answer of mine.

      这篇关于为什么使用基于括号的-Filter参数时$ PSItem的行为不符合预期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆