How do you execute an arbitrary native command from a string?

I can express my need with the following scenario: Write a function that accepts a string to be run as a native command.

It’s not too far fetched of an idea: if you’re interfacing with other command-line utilities from elsewhere in the company that supply you with a command to run verbatim. Because you don’t control the command, you need to accept any valid command as input. These are the main hiccups I’ve been unable to easily overcome:

  1. The command might execute a program living in a path with a space in it:

    $command = '"C:\Program Files\TheProg\Runit.exe" Hello';
    
  2. The command may have parameters with spaces in them:

    $command = 'echo "hello world!"';
    
  3. The command might have both single and double ticks:

    $command = "echo `"it`'s`"";
    

Is there any clean way of accomplishing this? I’ve only been able to devise lavish and ugly workarounds, but for a scripting language I feel like this should be dead simple.

4 Answers
4

Leave a Comment