Get-WMIObject -filter to accept variable?

rated by 0 users
This post has 3 Replies | 2 Followers

Top 50 Contributor
Posts 55
Swatto Posted: 05-17-2012 3:17 AM

Hello All,

I am trying to get Get-WMIObject -filter property to accept a variable from powershell, I am guessing this doesn't work as powershell creates variables as objects which the WQL language cannot process? (a complete guess here).

 I want the filtering to occur on the server, i do not want it to retrieve all the mailboxes and then filter through them on my client machine, is there a way to do this?

$name = Read-Host 'What is the Mailbox Display Name of the Person?'

Get-WMIObject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -filter {MailboxDisplayName="$name"} -computer exchangebox1,exchangebox2 | select-object MailboxDisplayName, Size, TotalItems, Servername | sort-object MailboxDisplayName | format-table MailboxDisplayName, TotalItems, @{l='Mailbox Size (MB)';e={$_.Size / 1KB -as [int]}}, Servername

The above code does not work, it does not accept the $name variable.

Please could you explain why this is, thanks Big Smile

 

Top 25 Contributor
Posts 287
Top Contributor

You dont need the brackets.

Try this:

-filter "MailboxDisplayName='$name'"

 

Top 50 Contributor
Posts 55

That's great Felipe, Thankyou Big Smile

For some reason -filter 'MailboxDisplayName="$name"' doesn't work but -filter "MailboxDisplayName='$name'" does - strange as I thought using single quotes in powershell does not substitute the variable name for the value?

Is there a reason for this please?

Top 25 Contributor
Posts 287
Top Contributor

Yes you are right.

Double quotes return the value of the variable and single quotes are interpreted as literals.

But because the single quotes are nested inside the double quotes it returns the string.

You can test it. Just get a variable and try "'$variable'"

You will get the string 'variable value'

Page 1 of 1 (4 items) | RSS
Copyright 2012 PowerShell.com. All rights reserved.