I am trying to create or get the result for the date and days with the Weeks, but somehow Powershell cannot do it for me:

(Get-Date '29/2/2020').addweeks(18)

The error I have received is like:

(New-TimeSpan -Start "$Get-Date" -End "(Get-Date '29/2/2020').addweeks(18)").ToString("dd' Days 'hh' Hours 'mm' Minutes 'ss' Seconds'") Method invocation failed because [System.DateTime] does not contain a method named 'addweeks'. At line:1 char:1 + (Get-Date '29/2/2020').addweeks(18) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound New-TimeSpan : Cannot bind parameter 'Start'. Cannot convert value "-Date" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." At line:3 char:22 + (New-TimeSpan -Start "$Get-Date" -End "(Get-Date '29/2/2020').addweek ... + ~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewTimeSpanCommand 

The output expected is:

Days, dd MM YYYY hh:mm AM/PM "dd' Days 'hh' Hours 'mm' Minutes 'ss' Seconds'" remaining until the date entered. 

1 Answer

New-TimeSpan's -Start and -End parameters expect arguments of type [DateTime], so you have to ensure your Get-Date commands get evaluated before being passed of to New-TimeSpan.

$now = Get-Date $18WeeksFromLeapDay = (Get-Date '29/2/2020').AddDays($(18 * 7)) $timespan = New-TimeSpan -Start $now -End $18WeeksFromLeapDay 

You can also omit the -Start argument completely and it will default to "right now" anyway:

$timespan = New-TimeSpan -End (Get-Date '29/2/2020').AddDays($(18 * 7)) 

I'd strongly suggest consulting the about_Parsing and about_Parameters help files to get a better understanding of how PowerShell evaluates command expressions and parameter arguments

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy