简体   繁体   中英

Using (*) in Where command in PowerShell

I am Using this command to get a Local User in Administrators group, and it works

Get-WmiObject -Class Win32_Groupuser -ComputerName $computer |? {$_.groupcomponent -like '*"Administrators"' -and $_.Partcomponent -like '*"User"'}|ft groupcomponent,Partcomponent

But now i want to use variable like this $Group="Administrators" $Account="users"

Get-WmiObject -Class Win32_Groupuser -ComputerName $computer |? {$_.groupcomponent -like *$Group -and $_.Partcomponent -like *$Account}|ft groupcomponent,Partcomponent

but i get nothing back

If the group name is "Administrators" you do not need to use a wildcard. The asterisk will match one or more characters. For example:

"Administrator*" matches Administrator, Administators, "Administrator Groups", etc

"*Administrators" matches Administrators, "Windows Administrators", etc

"*Administrator*" matches Administrators, "Administrator Groups", "Windows Administrators", etc

For the second command you can use a sub-expression to expand the variable.

Where-Object { $_.groupcomponent -like "*$($Group)*" }

This is a working example:

$Group = '"Administrators"'
Get-WmiObject -Class Win32_Groupuser -ComputerName $computer |? {$_.groupcomponent -like "*$Group"}

The same can be adapted for $_.partcomponent .

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