[英]How to query ManagedBy property of ADComputer in a Foreach loop?
I'm trying to generate a list of computers owned by a particular PDL and I'm encountering some syntax issues: 我正在尝试生成特定PDL拥有的计算机的列表,并且遇到一些语法问题:
$group = Get-ADGroupMember -Identity "pdl" | Select-Object -ExpandProperty DistinguishedName
Foreach($item in $group) { Get-ADComputer -Filter "ManagedBy -eq "$item"" -Property managedby | Select Name }
The second part is based on another code snippet that I found elsewhere (I think on StackOverflow as well) which worked just fine: 第二部分基于我在其他地方(我也认为也可以在StackOverflow上)找到的另一个代码片段,它工作得很好:
Get-ADComputer -Filter "ManagedBy -eq 'CN=user@company.com,OU=US,OU=Users,OU=Accounts,DC=americas,DC=company,DC=com'" -Property ManagedBy
But the difference is I could use '' in this one, but adding in $item prevents me from using that. 但是不同之处在于,我可以在这一行中使用'',但是在$ item中添加会阻止我使用它。
The syntax error I get back with the first snippet: 我在第一个代码段中发现了语法错误:
Get-ADComputer : A positional parameter cannot be found that accepts argument 'CN=user@company.com,OU=US,OU=Users,OU=Accounts,DC=americas,DC=company,DC=com'.
At D:\Documents\Scripts\uatgroup.ps1:2 char:31
+ Foreach($item in $UATgroup) { Get-ADComputer -Filter "ManagedBy -eq "$item"" -Pr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
Anyone know a way to fix the syntax here? 有人知道在这里修复语法的方法吗? Or an alternate method of running this?
还是运行此方法的替代方法?
This: 这个:
"ManagedBy -eq "$item""
Is parsed as three separate strings. 被解析为三个单独的字符串。 Only the first one (
ManagedBy -eq
) will be bound to the -Filter
parameter, the rest will be treated as separate tokens, causing PowerShell to complain that you can't just leave the string CN=...
there in the middle of everything. 只有第一个(
ManagedBy -eq
)将被绑定到-Filter
参数,其余的将被视为独立的令牌,从而导致PowerShell来抱怨,你不能离开字符串CN=...
有在中间一切。
You can either use single-quotes inside the double-quoted string, to avoid terminating the string early: 您可以在双引号字符串内使用单引号,以避免提早终止字符串:
Get-ADComputer -Filter "ManagedBy -eq '$item'"
Escape the inline double-quotes with a backtick ( `
): 使用反引号(
`
)转义内联双引号:
Get-ADComputer -Filter "ManagedBy -eq `"$item`""
Or escape them by doubling them: 或通过加倍它们来逃避它们:
Get-ADComputer -Filter "ManagedBy -eq ""$item"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.