PowerShell Function Run-CommandLine

So in this server build script that I’m working on there are several times when external executables are called, such as when I use the operator to call ICACLS for setting share permissions (& ICACLS.exe $folderName /GRANT $ADObject`:(OI)(CI)$ICACLSpermission). Sometimes calls can get messy with all the special characters involved, so I wrote a function that will parse a command line string and run it with Invoke-Expression.

function Run-Commandline {
        Runs a commandline executable with unlimited arguments.
        Uses space delimination to break the commandline up, then rejoin it back into an Invoke-Expression.  Special chatacters must be escaped! `
    .PARAMETER Commandline
        The command as you would run it from a command prompt.
        Run-Commandline -Commandline "C:\Windows\System32\netsh.exe advfirewall firewall add rule name=`"JON Monitoring`" protocol=TCP dir=in localport=16163,7080 action=allow"

    $cmd,$args = $CommandLine -split ' '
    $args = $args | foreach {"'$_'"}
    $args = $args -join ' '
    $cmdLine = $cmd + ' ' + $args
    Invoke-Expression $cmdLine
This entry was posted in Programming and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s