views:

35

answers:

1

I have a set of commands that I'd like to run and do some returncode checks against the result, so i figured it would be easy to put them into an array for execution.

Let's take this one as an example:

C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section system.webServer/webdav/authoring /enabled:true /commit:apphost

Now, when I put it into my array without any quotes it's immediately interpreted as a command, the command is executed and the result is written into the array:

$commands = @()
$commands += C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section system.webServer/webdav/authoring /enabled:true /commit:apphost

When I use quotes to put it into the array as a string, trying to execute it doesn't work.

PS> $commands = @()
PS> $commands += "C:\windows\system32\inetsrv\AppCmd.exe set config ""Default Web Site/"" /sectio n:system.webServer/webdav/authoring /enabled:true /commit:apphost"
PS> $commands[0]
C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section:system.webServer/webdav/authoring /enabled:true /commit:apphost
PS> & $commands[0]
The term 'C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section:system.webServer/webdav/authoring /enabled:true /commit:apphost' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
        At line:1 char:2
        + & <<<<  $commands[0]
            + CategoryInfo          : ObjectNotFound: (C:\windows\syst.../commit:apphost:String) [], CommandNotFoundException
            + FullyQualifiedErrorId : CommandNotFoundException

So, how do I correctly put this command into an array, queue or whatever fits best so I can execute it when the time is right?

+1  A: 

When you use the call operator & the string following it must name only the command to be executed - not any parameters. With what you have configured you can use Invoke-Expression instead e.g.:

iex $command[0]

One warning about Invoke-Expression, be careful using this command if any input comes from the user as it can be used to inject unwanted commands e.g.:

Read-Host "Enter commit value"
Enter commit value: apphost; remove-item c:\ -r -force -ea 0 -confirm:0 #
Keith Hill
Ah, invoke-expression it is. I tried invoke-command. Guess I have to read the documentation better next time. Thanks!
Christoph Voigt