Answered by:
PS: comparing time

Question
-
Hi,
I'm writing a small script which sees how much it takes to load a webpage, when it takes more then 300 ms, it should do something. However, with a value of 89 it already shows as greater or equal to 300 (Timetaken is 89 => True).
I probably need to convert $Timetaken to a correct value(?)Please advise.
The script:
$URL = 'http://www.google.com'
$Start = Get-Date
$PageRequest = $Request.DownloadString($URL)
$TimeTaken = '{0:N0}' -f ((Get-Date) – $Start).TotalMilliseconds
write-output "Timetaken is $TimeTaken"
$TimeTaken -ge 300
Timetaken is 89
True$TimeTaken | gm
TypeName: System.String
Jan Hoedt
Tuesday, June 14, 2016 11:26 AM
Answers
-
This is where we would use Measure-Command
$ts=Measure-Command { $PageRequest = $Request.DownloadString($URL) } if($ts.TotalMilliseconds -gt 300){ 'Too long' }
\_(ツ)_/
- Marked as answer by janhoedt Thursday, June 16, 2016 11:56 AM
Tuesday, June 14, 2016 1:48 PM
All replies
-
Hi Jan,
that is because a string starting with 8 is greater than a string starting with 3. Switch the position of 300 and $TimeTaken (and switch the operator to -lt) and you'll be fine.
Cheers,
FredEdit: This is because when comparing two objects of different types, PowerShell will try to convert the second object into the type of the first: So if the number 300 comes first, it will try to convert the string 89 to int (works; only for the comparison, $TimeTaken will still be a string).
However, when you place the string 89 first, it will convert the number 300 to string, where "89" is greater "300"
There's no place like 127.0.0.1
- Edited by FWN Tuesday, June 14, 2016 11:35 AM
Tuesday, June 14, 2016 11:32 AM -
I see. What would be the good approach then?
Jan Hoedt
Tuesday, June 14, 2016 12:44 PM -
You can also do this
[Int32]$TimeTaken = ((Get-Date) – $Start).TotalMilliseconds write-output "Timetaken is $TimeTaken" $TimeTaken -ge 300
Tuesday, June 14, 2016 12:52 PM -
I see. What would be the good approach then?
Jan Hoedt
Hi Jan,
if you need to have it as a string, use the approach described in my first paragraph. If not, don't convert to string.
Cheers,
FredThere's no place like 127.0.0.1
Tuesday, June 14, 2016 12:59 PM -
This is where we would use Measure-Command
$ts=Measure-Command { $PageRequest = $Request.DownloadString($URL) } if($ts.TotalMilliseconds -gt 300){ 'Too long' }
\_(ツ)_/
- Marked as answer by janhoedt Thursday, June 16, 2016 11:56 AM
Tuesday, June 14, 2016 1:48 PM -
try this :
$URL = 'http://www.google.com'
$Start = Get-Date
$PageRequest = $Request.DownloadString($URL)
$TimeTaken = ((Get-Date) – $Start).TotalMilliseconds
write-output "Timetaken is $('{0:N0}' -f $TimeTaken)"
$TimeTaken -ge 300=> you have to format number in write-output, not in the variable value.
Tuesday, June 14, 2016 1:58 PM