Thursday, November 21, 2013

Dynamically invoking commands in PowerShell

If you ever have to build a command to execute dynamically in PowerShell, this is a very good discussion thread on how to accomplish this: http://stackoverflow.com/questions/6338015/in-powershell-how-do-you-execute-an-arbitrary-native-command-from-a-string

It basically involves using the Invoke-Expression or iex command for invoking the command contained in your PowerShell string.

Therefore, you can build up your PowerShell command in a PowerShell string, and then simply invoke it using Invoke-Expression or the short form iex.

Here is an example script that simply executes a dynamic command to run MSBuild:
 
$MSBuildPath = "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe"
$MSBuildFilePath = "H:\Scripts\RunPowerShell.proj"


$MSBuildCmd = "$MSBuildPath $MSBuildFilePath `"/p:AppPoolName=TestAppPool;AppPoolVersion=v4.0`""

Clear-Host
Write-Host $MSBuildCmd
Invoke-Expression $MSBuildCmd




 

No comments:

Post a Comment