View Single Post
Old 10-29-2006   #1 (permalink)
OK


 
 

unexpected conversion for [System.DateTime]

Guys,
I run some asynchronous scripts and need to measure their timing:
I run into following “unexpected” conversion, below is a small script to
demonstrate it.

The question is:
Why [System.DateTime]::Now gets converted to [String] type when passed as
parameter, while a variable of [System.DateTime] type is not?
Doesn’t is look like an inconsistent behavior?

#------------------------------------------------------------------------------
function test([DateTime] $a) {

Start-Sleep -milli 200
[DateTime] $private:b = [System.DateTime]::Now
Start-Sleep -milli 200


@"
A started $a. A elapsed time $($b - $a)<br>
B started $b. B elapsed time $([System.DateTime]::Now - $b)<br>
Total elapsed time $([System.DateTime]::Now - $a)<br>
"@

}


#------------------------------------------------------------------------------
function test2($a) {
$a.GetType()
}


#------------------------------------------------------------------------------
#-- Main script
---------------------------------------------------------------
#------------------------------------------------------------------------------


# Works fine
[DateTime] $private:x = [System.DateTime]::Now
test $x
test2 $x


# Doesn't work
test [System.DateTime]::Now
test2 [System.DateTime]::Now

return

#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------

> ./g

A started 10/29/2006 13:24:24. A elapsed time 00:00:00.2031224<br>
B started 10/29/2006 13:24:24. B elapsed time 00:00:00.2031224<br>
Total elapsed time 00:00:00.4062448<br>

IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
test : Cannot convert value "[System.DateTime]::Now" to type
"System.DateTime". Error: "String was not recognized as a valid DateTime."
At .\g.ps1:37 char:5
+ test <<<< [System.DateTime]::Now
True True String System.Object


My System SpecsSystem Spec