Execute cmdlet out of a variable

Hello guys,

I have a little problem and I'm not sure if it's even possible to solve. So i was thinking to ask the experts ;)

I have simple file (e.g. .txt) with a cmdlet. I can access these file and read the content. In the end i have this command in simple string variable.

Is it possible to tell Powershell that he should execute this cmdlet instead of just give me the value?

Thanks in advance :)

  • You can use the PowerShell call operator "&". Here is a simple example:

    $a = "Get-Process"
    & $a

    There is a caveat with using this since the call operator can only operate against a single command. If you were to modify the above like this:

    $a = "Get-Process w*"
    & $a

    you will get an error. To get around this use Invoke-Expression as follows:

    $a = "Get-Process w*"
    Invoke-Expression $a

    See Get-Help Invoke-Expression -examples to get more examples on the usage of Invoke-Expression.

Reply Children
No Data