PowerShell - 为 -Filter 使用对象变量

PowerShell - using an objects variable for -Filter

我不知道为什么这不起作用,甚至不知道要搜索什么。

我有一个简单的函数 Get-FileInput。它只是调用 Import-CSV 并在传递数据之前检查特定列。

我有 $filterType = "Name"

我的测试 TSV 格式为

db stuff Name 1 2 spare40

那我有这个

$data = Get-FileInput
foreach ($computer in $data)
{
    Get-ADComputer -Filter {$filterType -eq "comp1"} | Format-Table
    Write-Host "$($computer.$filterType)"
    Get-ADComputer -Filter {$filterType -eq "$($computer.$filterType)"} | Format-Table
}

第一个 Get-ADComputer 工作正常并输出 table。

Write-Host 在终端中产生输出 comp1。

第二个 Get-ADComputer 运行,但不输出任何内容。

不要使用 脚本块 ({...}) 作为 -Filter 参数 - 它适用于简单的情况(例如,{$filterType -eq "comp1"}),但在更复杂的情况下会分崩离析({$filterType -eq "$($computer.$filterType)"})。

-Filter 参数是 [string] 类型,您应该这样构造它:

Get-ADComputer -Filter "$filterType -eq '$($computer.$filterType)'" | Format-Table

有关背景信息,请参阅我的 this answer