Rarely, but sometimes we need to run the command from an expression that we create. I stumbled upon a situation where I was to read the content of a config file and run it.
There could be other ways to do it, but invoke-expression can be used with simplicity.
Invoke-Command
SYNTAX
Invoke-Command [-ScriptBlock] <scriptblock> [-NoNewScope] [-InputObject <psobject>] [-ArgumentList <Object[]>]
[<CommonParameters>]
EXAMPLE:
Read content of a file that has EXPRESSION=get-help ls
$str=gc "c:\temp\cmd_list.txt" | where { $_ -match "EXPRESSION=" } | foreach { $_.split("=")[1]
invoke-command $str
I hope it was quite easy and simple.
Happy scripting !!!