11

In a Powershell script, I something like this:

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

I want to pipe all output, errors etc of this to the string $output

How can I do this? I've tried > at the end as well as $output = ... but neither seem to catch errors and the sort.

JBurace
  • 5,123
  • 17
  • 51
  • 76

1 Answers1

15

Try this:

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

The use of the call operator & is unnecessary as is quoting the exe path in this case since the path doesn't contain spaces. If the path contained spaces, then it would need to be quoted and then you would have to use the call operator. That said, I'm not sure why you need to use Invoke-Expression at all in this case. The following would work just as well given your example.

$output = C:\Scripts\psftp.exe ftp.blah.com 2>&1
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • I won't be touching the command prompt (it'll be automated), how can I do this within the script? – JBurace Sep 07 '12 at 14:56
  • That is script. Anything you type at the command prompt can be dropped into a script and executed i.e. automated. The only exception I can think of are commands that require user input like Read-Host. Does executing the psftp.exe in this fashion prompt for input? – Keith Hill Sep 07 '12 at 14:57
  • I'll add that this will typically return an array of strings; if you want all of the output captured as a single string, append "| Out-String" onto the end of the command. – deadlydog Aug 09 '14 at 22:17
  • I get an error. Illegal character in path! My Path has spaces, so I have all in double qutoes – J86 Aug 01 '16 at 09:03
  • See [this thread](http://stackoverflow.com/questions/38693278/powershell-mysql-backup-script-error-in-task-scheduler-0x00041301). – J86 Aug 01 '16 at 09:16
  • What if I am executing a variable `$cmd` that is a block with multiple lines> `output = Invoke-Expression $cmd` – How can I store all STDOUT and STDERR into a variable? – Ωmega Aug 18 '23 at 15:48