Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generate command-line command, then invoke using powershell

Tags:

powershell

Using powershell, you can use the '&' character to run another application and pass in parameters.

A simple example.

$notepad = 'notepad' $fileName = 'HelloWorld.txt'  # This will open HelloWorld.txt & $notepad $fileName    

This is good. But what if I want to use business logic to dynamically generate a command string? Using the same simple example:

$commandString = @('notepad', 'HelloWorld.txt') -join ' '; & $commandString 

I get the error:

The term 'notepad HelloWorld.txt' 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.

In my real example I'm trying to dynamically add or remove options to the final command line string. Is there a way I can go about this?

like image 459
Andrew Shepherd Avatar asked Jul 06 '11 23:07

Andrew Shepherd


People also ask

Can PowerShell run CMD commands?

Many legacy Command Prompt (CMD) commands work in the Windows PowerShell scripting environment. The PowerShell environment carries these commands forward from the most used commands like ping to the most informational commands like tracert from the legacy environment using aliases.

What is IEX command in PowerShell?

iex is an alias for Invoke-Expression . Here the two backticks don't make any difference, but just obfuscates the command a little. iex executes a string as an expression, even from pipe. Here Start-Process is a cmdlet that starts processes.

What is invoke command in PowerShell?

The Invoke-Command cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. Using a single Invoke-Command command, you can run commands on multiple computers. To run a single command on a remote computer, use the ComputerName parameter.


1 Answers

Two ways to do that:

Separate the exe from the arguments. Do all your dynamic stuff for the arguments, but call the exe as normal with the variable holding the arguments afterward:

$argument= '"D:\spaced path\HelloWorld.txt"' $exe = 'notepad' &$exe $argument  #or notepad $argument 

If you have more than one argument, you should make it an array if it will be separate from the exe part of the call:

$arguments = '"D:\spaced path\HelloWorld.txt"','--switch1','--switch2' $exe = 'notepad' &$exe $arguments 

Use Invoke-Expression. If everything must be in a string, you can invoke the string as if it were a normal expression. Invoke-Expression also has the alias of iex.

$exp = 'notepad "D:\spaced path\HelloWorld.txt"' Invoke-Expression $exp 

In either case, the contents of the arguments and of the exe should be quoted and formatted appropriately as if it were being written straight on the commandline.

like image 118
Joel B Fant Avatar answered Sep 19 '22 21:09

Joel B Fant