用 Get-ADGroup 中的变量替换字符串 [英] Replacing a string with a variable in Get-ADGroup
问题描述
我正在尝试使用 PowerShell 在 AD 中搜索组名称.
I'm trying to use PowerShell to search AD for Group Names.
为什么这些都不起作用,param 或 Read-Host
?两者都传递字符串,但结果为空.但是,如果我将命令中的变量 $ADGroup
替换为实际的组名(字符串)并运行命令 Get-ADGroup...代码> 结果按预期提供.我尝试用单引号替换双引号,但得到了相同的结果,该命令可以单独运行,但
Read-Host
或 param 均不提供信息.我不明白为什么当它是一个变量 ($ADGroup
) 时没有传递字符串.谢谢.
Why don't either of these work, the param or the Read-Host
? Both are passing strings, but the results are empty. However, if I replace the variable $ADGroup
in the command with an actual Group Name (a string) and run the command Get-ADGroup...
results are provided as expected. I tried to replace the double quotes with single quotes and I get the same results, the command works alone but neither Read-Host
or param provide information. I can't figure out why the string isn't being passed when it's a variable ($ADGroup
). Thanks.
param(
[Parameter(Mandatory=$true)]
[string]$ADGroup
)
# One or the other param or Read-Host
$ADGroup = Read-Host "Enter Group Name"
PS > Get-ADGroup -Filter {name -like "*$ADGroup*"} -Properties * | Select-Object -Property Name
Get-ADGroup -Filter {name -like '*GroupName*'} -Properties * | Select-Object -Property Name
Name
----
Results
Results
Results
Results
Results
推荐答案
这是使用基于 脚本块 的过滤器 (-Filter {...}
) 在 ActiveDirectory 模块 是不推荐的.
This is one of the reasons why using a script block based filter (-Filter {...}
) on the cmdlets of the ActiveDirectory Module is not recommended.
来自 ActiveDirectory 模块的 Get-*
cmdlet 的 Parameter 部分中的 -Filter
声明如下:
The -Filter
on the Parameter section of the Get-*
cmdlets from ActiveDirectory Module states the following:
-过滤器
指定检索 Active Directory 对象的查询字符串.此字符串使用 PowerShell 表达式语言 语法.PowerShell 表达式语言语法为 Filter 参数接收的值类型提供了丰富的类型转换支持.语法使用有序表示,这意味着运算符位于操作数和值之间.
-Filter
Specifies a query string that retrieves Active Directory objects. This string uses the PowerShell Expression Language syntax. The PowerShell Expression Language syntax provides rich type-conversion support for value types received by the Filter parameter. The syntax uses an in-order representation, which means that the operator is placed between the operand and the value.
- 查询字符串:
Get-ADGroup -Filter "name -like '*$ADGroup*'"
- LDAP 查询字符串:
Get-ADGroup -LDAPFilter "(name=*$ADGroup*)"
有效过滤的推荐文档:
注意:值得一提的是,在查询 Active Directory 时,您将希望仅从 AD 对象中检索所需的属性,尤其是在查询大型域/森林时.使用 -Properties *
是一种不好的做法,而且效率也很低,这会减慢您的查询速度,因为它正在检索被查询对象的所有可用属性.
Note: Worth mentioning, when querying Active Directory you will want to retrieve only the needed attributes from the AD Objects, specially when querying big Domains / Forests. Using -Properties *
is a bad practice and also very inefficient, this will slow down your query as it is retrieving all available attributes of the objects being queried.
这篇关于用 Get-ADGroup 中的变量替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!