Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

$ts = New-TimeSpan -Days 5
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
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")

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


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.