How to connect Invoke-Expression output to a string?

In a Powershell script, I am something like this:

Invoke-Expression "& `"C:\Scripts\psftp.exe`" ftp.blah.com" 

I want to pass all output, errors, etc. to the string $output

How can i do this? I tried > at the end, as well as $output = ... , but didn't seem to find any errors or sorting.

+7
source share
1 answer

Try the following:

 $output = Invoke-Expression "C:\Scripts\psftp.exe ftp.blah.com 2>&1" 

The use of the & call operator is not necessary since it quotes the EXE path in this case, since the path does not contain spaces. If the path contains spaces, then it will need to be quoted, and then you will have to use the call operator. However, I'm not sure why you need to use Invoke-Expression at all in this case. The following will work just like your example.

 $output = C:\Scripts\psftp.exe ftp.blah.com 2>&1 
+12
source

All Articles