Pete
Pete

Reputation: 1305

supplying filter value as variable in powershell yields different results

I'm trying to do bulk operations on a set of mailboxes on my Exchange 2010 server. To limit the number boxes I need to operate on, I want to filter the results. I know the ones I need to work on are created after 2015-01-01, so I am supplying this as a filter value (which works):

$boxes = Get-Mailbox -filter { whenCreated -gt '2015-01-01' }

I want to be able to reuse my script later at some point, so I tried to set this up to take a parameter, but its returning all the boxes (does not work)...

$filterdate = '2015-01-01'; $boxes = Get-Mailbox -filter { whenCreated -gt $filterdate }

My guess is that -Filter is doing some sort of implicit type conversion when I supply a string literal vs when I supply a string variable

How can I supply -Filter with a variable?

edit:

this also returns an unfiltered list:

$filterdate = [System.DateTime]'2015-01-01'; get-mailbox -filter { whencreated -gt $filterdate }

results in error:

$filterdate = '2015-01-01'; get-mailbox -filter { whencreated -gt "$filterdate" }

Upvotes: 1

Views: 626

Answers (1)

Matt
Matt

Reputation: 46710

I'm sure the issue was the the variable $filterdate did not exist in the scope of the scriptblock you made { whencreated -gt "$filterdate" }. The syntax is fine.... until you add variables to the mix. Pretty sure, inside that scope, $filterdate would have been null. Then you were getting all the mailboxes because anything is greater than null (accept itself of course).

1 -gt $null
"asdf" -gt $null
True

Using a properly quoted string you can get the same result.

-filter "whencreated -gt '$filterdate'"

Upvotes: 1

Related Questions