Using a ScriptBlock to pass a variable into another variable

So, during the course of my current project, I've been able to re-use a lot of scripts that I've spent years developing and reworking.  This time through, though, I've found that in trying to make them consumable by other people, I need to update them with command-line parameters (you know, like some sort of grown-up scripter).

One of the environments I'm working with is fairly large, and it's very impractical to do client-side filtering (a Get-Mailbox -ResultSize Unlimited, for example, takes about 8 hours to complete, if my session doesn't time out).  There are very few instances where I actually need *all* mailboxes returned to perform an operation; I'm usually working with a single department or subset of users at a time, and can filter on a domain name.

Server-side filtering is the answer.  However, making a function that I can use repeatedly is almost just as important (if for no other reason, than I constantly forget how I did something).

Normally, I could just use something like:

Get-Maibox -ResultSize Unlimited -Filter { WindowsEmailAddress -like "*" }

and call it a day.  However, if I want to create something that I can continue to reuse, I need to be able to specify data in the -Filter parameter on-the-fly, such as in a parameter.

Here's the solution I came up with.  In this example, I want to select mailboxes for the domain "" in my gigundous tenant.

Function MakeFilter($FilterValue)
     If ($FilterValue.StartsWith("*"))     
          # Value already starts with an asterisk     
          $FilterValue = "*" + $FilterValue    
     $Filter = [scriptblock]::Create("{WindowsEmailAddress -like `"$FilterValue`"}")
     Write-Host $Filter

So, giving it a try:


Comments (1)

  1. Turbomcp says:

    another one i missed:)
    i think this plus the link i put on newer post would cut time dramatically.
    for me on 30k environment i get all data(5-7 attributes im interested in)i need from all mailboxes in around 2min without using this filter, combined with this(don’t know if its possible) should be even faster
    Thanks again

Skip to main content