I have a Powershell script that (as one of its options) reads a user-defined pre-execution command from a file and needs to execute it. The user-defined pre-execution command is expected to be an ordinary DOS-style command. I can split the command by spaces and then feed it to the PowerShell "&" to get it executed:
$preExecutionCommand = "dir D:\Test"
$preExecutionArgs = $preExecutionCommand -split '\s+'
$preExecutionCmd = $preExecutionArgs[0]
$preExecutionNumArgs = $preExecutionArgs.Length - 1
if ($preExecutionNumArgs -gt 0) {
$preExecutionArgs = $preExecutionArgs[1..$preExecutionNumArgs]
& $preExecutionCmd $preExecutionArgs
} else {
& $preExecutionCmd
}
But if the user-defined command string has spaces that need to go in the arguments, or the path to the command has spaces, then I need to be much smarter at parsing the user-defined string.
To the naked eye it is obvious that the following string has a command at the front followed by 2 parameters:
"C:\Program Files\Tool\program1" 25 "the quick brown fox"
Has anyone already got a function that will parse strings like this and give back an array or list of the DOS-style command and each of the parameters?