SwimBikeRun
SwimBikeRun

Reputation: 4460

How to use output redirection in powershell's command-measure?

How to use output redirection in powershell's command-measure?

I want something similar to time from Linux, a simple program to time how long a program runs

I thought this would work, but the std out doesn't redirect: Measure-Command {start-process python printstuff.py > Output.txt -Wait}

Example Input:

Measure-Command {echo hi}

Example Output:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 1318
TotalDays         : 1.52546296296296E-09
TotalHours        : 3.66111111111111E-08
TotalMinutes      : 2.19666666666667E-06
TotalSeconds      : 0.0001318
TotalMilliseconds : 0.1318

Upvotes: 0

Views: 1779

Answers (1)

Duncan
Duncan

Reputation: 95642

The problem is that Start-Process doesn't write to standard output. Instead it creates a new console window and runs the process with its standard output set to the console window. Using the redirection operator will redirect stdout for Start-Process but as it doesn't write to stdout you get an empty file.

The solution is to use the -RedirectStandardOutput option to tell Start-Process to redirect stdout for the process it started.

Measure-Command { Start-Process python printstuff.py -RedirectStandardOutput output.txt -Wait }

Note that if you want to pass any options to the python program you will have to specify -ArgumentList explicitly:

Measure-Command { Start-Process python -ArgumentList ('printstuff.py','-opt') -RedirectStandardOutput output.txt -Wait }

The messiness of -ArgumentList means that unless you really do need to use Start-Process you will probably find it easier just to drop it and then the redirection works normally:

Measure-Command { python printstuff.py >output.txt }

Note that if you want to quote the name of the executable (or use a value in a variable) you will need to use the call operator (I mention this as I wonder whether this is why you were looking at Start-Process in the first place):

Measure-Command { & "C:\Python34\python" printstuff.py >output.txt }

Upvotes: 1

Related Questions