PowerShell How to execute a collection of commands stored as strings

So if you follow my PowerShell profile github repo I have a few git function built.  The company I work for like many other companies has components spread out among multiple solutions.  I got tired of switching between solutions to do a git pull.  What do developers do when they get tired of a repetitive task, we script it.  Here is a simple example to get you on your way:

Lets say we have a repetitive task where we run three cmd-lets over and over multiple times a day.

We might create a PowerShell function that looks like this:

function repetitiveWork{
    Get-Process
    doSomething
    Get-ChildItem C:\Temp
    doSomething
    Get-Process
    doSomething
}

function doSomething{
 #somecode
}

Now in my mind the call to doSomething is repetitive and violates the Don’t Repeat Yourself (DRY) principle.  In PowerShell there is a cmd-let that will allow us to run a function that is stored as a string value it is Invoke-Expression.

Using the Invoke-Expression cmd-let we can turn the code above into this:

function repetitiveWork{
    $arrayOfCommands = "Get-Date","Get-ChildItem C:\Temp", "Get-Process"
    foreach($a in $arrayOfCommands){
         Invoke-Expression $a    
         doSomething
    }
}

function doSomething{
 #somecode
}
Advertisement
This entry was posted in PowerShell and tagged . Bookmark the permalink.

1 Response to PowerShell How to execute a collection of commands stored as strings

  1. test website says:

    I got what you intend, thankyou for posting .Woh I am pleased to find this website through google. “Finley is going over to get a new piece of bat.” by Jerry Coleman

Comments are closed.