PowerShell: Frame Command expressions in variables and execute the commands via Variable values

I often find the need to dynamically frame a command syntax and run the ultimate command:

 

Sample Script:

$var = 10
$cmd = "write-host $var"
Write-Host "Command is: $cmd"
Write-Host "Command Result is: "
invoke-expression -command "$cmd"

 

Script Result:

PS C:Temp> .Run-commands-via-variables.ps1
Command is: write-host 10
Command Result is:
10
PS C:Temp>

 

Sample Script#2:

param ([String]$msg)
$cmd = "write-host $msg"
Write-Host "Command is: $cmd"
Write-Host "Command Result is: "
invoke-expression -command "$cmd"

Script Result#2:

PS C:Temp> .Run-commands-via-variables.ps1 Message
Command is: write-host Message
Command Result is:
Message
PS C:Temp>

Leave a Reply

Your email address will not be published. Required fields are marked *