You can use Invoke-Expression
, however, keep in mind that there are security considerations to ponder when using this cmdlet, as it may open you up to code-injection attacks. Also note that Invoke-Expression
will usually succeed even when the underlying command fails with an error.
$command = "myapp.exe '$((get-date -Uformat %s).remove(10, 1).substring(5,9))'"
Invoke-Expression $command
If you want to check the success of your command, check $LASTEXITCODE
for a suitable exitcode and continue/fail based on that. Note that $LASTEXITCODE
only works when checking the result of a program, not a cmdlet.
Avoiding Invoke-Expression
You can avoid the use of Invoke-Expression
by building an array of arguments to pass to your command line application, like so (in your case, it would just be one argument but this can be expanded to build out more complex commands with more than one argument as well, just add additional array elements for each switch, parameter, or value):
$cmdargs = @(
( GetDdate -Uformat %s ).Remove( 10, 1 ).Substring( 5,9 )
)
myapp.exe $cmdargs
You can still track success of the command by checking the value of $LASTEXITCODE
.
Keeping it simple
In your case, you can just call myapp.exe (get-date -Uformat %s).remove(10, 1).substring(5,9)
which will insert the date string as an argument. But the above techniques (building an array is the preferred method to Invoke-Expression
) becomes useful when you want to build a more complex command based on a number of conditions.