简体   繁体   中英

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:

$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:

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.

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.

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"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM