Dynamically generate command-line command, then invoke using powershell

Two ways to do that:

  1. 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:

    $exe="notepad"
    $argument=""D:\spaced path\HelloWorld.txt""
    &$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:

    $exe="notepad"
    $arguments=""D:\spaced path\HelloWorld.txt"",'--switch1','--switch2'
    &$exe $arguments
    
  2. 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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)