【问题标题】:Using "-Filter" with a variable对变量使用“-Filter”
【发布时间】:2014-11-13 20:45:44
【问题描述】:

我尝试过滤掉这样的东西:

Get-ADComputer -Filter {name -like "chalmw-dm*" -and Enabled -eq "true"} ...

这就像一个魅力,得到我想要的……

现在我想要“name -like ...”部分作为这样的变量:

Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"} |

我检查了几个问题(例如,PowerShell AD Module - Variables in Filter),但这对我不起作用。

我尝试了以下方法:

$nameRegex = "chalmw-dm*"
$nameRegex = "`"chalmw-dm*`""

在Get-ADComputer 命令中也有' 和没有。

谁能给我一些提示?

【问题讨论】:

  • 变量不插在单引号字符串中。

标签: powershell filter


【解决方案1】:

试试这个:

$NameRegex = "chalmw-dm"  
$NameR = "$($NameRegex)*"
Get-ADComputer -Filter {name -like $NameR -and Enabled -eq $True}

【讨论】:

    【解决方案2】:

    你不需要在变量周围加上引号,所以只需改变这个:

    Get-ADComputer -Filter {name -like '$nameregex' -and Enabled -eq "true"}
    

    进入这个:

    Get-ADComputer -Filter {name -like $nameregex -and Enabled -eq "true"}
    

    但是请注意,过滤语句的脚本块表示法具有误导性,因为该语句实际上是一个字符串,所以最好这样写:

    Get-ADComputer -Filter "name -like '$nameregex' -and Enabled -eq 'true'"
    

    Related。 Also related.

    还有 FTR:您在此处使用通配符匹配(运算符 -like),而不是正则表达式(运算符 -match)。

    【讨论】:

      【解决方案3】:

      或者

      -like '*'+$nameregex+'*'
      

      如果您想使用通配符。

      【讨论】:

        【解决方案4】:

        添加双引号

        $nameRegex = "chalmw-dm*"
        

        -like "$nameregex" 或 -like "'$nameregex'"

        【讨论】:

          猜你喜欢
          • 2016-03-17
          • 2021-04-16
          • 1970-01-01
          • 2019-12-24
          • 2013-10-10
          • 2018-02-15
          • 1970-01-01
          • 1970-01-01
          • 2019-12-29
          相关资源
          最近更新 更多