Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

When using PowerShell, why can I not use the overloaded ToString() methods for the TimeSpan structure?

$ts = New-TimeSpan -Days 5
$ts.ToString("g")
Cannot find an overload for "ToString" and the argument count: "1".
At line:1 char:13
+ $ts.ToString <<<< ("g")
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

Is there a workaround?

share|improve this question
    
What output are you expecting exactly? Looking at $ts | Get-Member shows a single, parameterless overload, which on my laptop gives 5.00:00:00 which seems similar to passing ToString("g"). What are you specifically after? –  Ben Pilbrow Aug 25 '11 at 19:13
    
Sorry, that "g" was a random format I pulled out of my hat. I can extract the numbers I need using the TimeSpan properties and format them manually, but I don't really want to (shouldn't have to) do that. When I asked for a workaround, I really meant for me to be able to access the methods that would be available if I was working in C#. –  pk. Aug 25 '11 at 19:26
    
Oh right, I understand. In that case, I'm not sure you'll find what you want, apart from things like "It's been " + $ts.Hours + " hours and "+ $ts.Days +" days since you took your love away". Cheesy song reference, sorry about that! –  Ben Pilbrow Aug 25 '11 at 19:35

1 Answer 1

up vote 4 down vote accepted

I think what is going on is that you want the .NET 4 version of TimeSpan.ToString(), which has 2 overloads, and you are getting the .NET 3.5 version of TimeSpan.ToString(), which does not have any overloads. If you look at this question on StackOverflow it shows how to get PS to use the .NET 4 assemblies.

[Addition] After creating the config file per the link above, I was able to get the following to execute successfully:

PS C:\Scripts > add-type -Path "C:\Windows\Microsoft.NET\framework64\v4.0.30319\mscorlib.dll"

PS C:\Scripts > $ts = New-Object -Type System.TimeSpan

PS C:\Scripts > $ts.Tostring("g")

0:00:00
share|improve this answer
    
I'd definitely say use the config file answer rather than the registry key. The registry key could be quite nasty on some apps, forcing them to use the latest version of .net. –  Ben Pilbrow Aug 25 '11 at 20:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.