One astute attendee asked if it was possible to create dynamic PowerShell in a script. Or put another way, can you define a PowerShell statement in a variable and then tell PowerShell to execute the contents of that variable. I’d never tried that so I didn’t know the answer. I said as much and speculated that it was possible and that I’d check into it for him.

Fortunately, there are a lot of really smart and knowledgeable people at conferences; not all of them speak. That can sometimes be intimidating; it can also be very helpful. Another attendee came up to me after the session and showed me this little script.

Executing Dynamic PowerShell

In the script, the $cmd variable is assigned a literal value that is itself a PowerShell statement. You could substitute any valid PowerShell statements in place of Get-Process. The second line is where it gets interesting. Enclosing the variable in parenthesis and prefacing it with an ampersand tells PowerShell to evaluate the contents of the variable and execute those dynamically.

$cmd = ‘Get-Process’;
&($cmd);

When I ran this script, I received a list of processes running on my local computer.

With this simple example, you may ask “What’s the point? Why not execute Get-Process directly?” I can see instances where you may need to dynamically build statements that include aspects that are not known at design-time. For example, passing in a sort or filter criteria, a machine name, or even a SQL Server instance name.

I wish I’d gotten the name of the attendee that showed this to me; I’d give him credit for this. So to the unknown Posher, thank you.