0

I'm trying to capture the Verbose, Error and other streams of a PowerShell script in a file. This to monitor the output of my script.

The following code works fine:

$LogFile    = 'S:\ScriptLog.log'
$ScriptFile = 'S:\TestieScript.ps1'

powershell -Command $ScriptFile *>&1 > $LogFile

However, the moment I try to put a space in one of the file paths, it's no longer working. I tried a lot of things, like double quotes, single quotes, .. but no luck.

To illustrate, the following code doesn't work:

$LogFile    = 'S:\ScriptLog.log'
$ScriptFile = 'S:\Testie Script.ps1'

powershell -Command $ScriptFile *>&1 > $LogFile

One person in this thread has the same issue.

Thank you for your help.

Community
  • 1
  • 1
DarkLite1
  • 13,637
  • 40
  • 117
  • 214

2 Answers2

2

try using -file parameter:

powershell -file $ScriptFile *>&1 > $LogFile
CB.
  • 58,865
  • 9
  • 159
  • 159
2

You're trying to run a file whose name contains a space as a command without proper quoting, so you're most likely getting an error like this in your log:

The term 'S:\Testie' is not recognized as the name of a cmdlet, function, script file, or operable program.

Either add proper quoting (and the call operator &, because your path is now a string):

powershell -Command "& '$ScriptFile'" *>&1 > $LogFile

or (better) use the -File parameter, as @CB. already suggested:

powershell -File $ScriptFile *>&1 > $LogFile

which has the additional advantage that the call will return the actual exit code of the script.

Edit: If you want to run the command as a scheduled task you'll need to use something like this:

powershell -Command "& 'S:\Testie Script.ps1' *>&1 > 'S:\ScriptLog.log'; exit $LASTEXITCODE"

because the redirection operators only work inside a PowerShell process.

Community
  • 1
  • 1
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • Thank you Ansgar, this works flawlessly in the ISE. I'm now trying to put this in a Scheduled task as following: `Program: Powershell` and `Arguments: -ExecutionPolicy Bypass -File "S:\Testie Script.ps1" *>&1 > "S:\ScriptLog.log"`. But this doesn't even generate a file.. – DarkLite1 Aug 19 '15 at 11:05