I am trying to get the difference in days between a string datetime and the current date. I tried following code on my local PC
$Dateinname = "24-05-2022"
$Retention = (New-TimeSpan -Start $DateInName -End (get-date)).Days
if ($Retention -gt 14){
//do something
}
However in Automation Account 'Powershell script', the same code provides following error:
New-TimeSpan : Cannot bind parameter 'Start'. Cannot convert value "[datetime]::parseexact" to type "System.DateTime". Error: "String was not recognized as a valid DateTime." At line:72 char:43 ... $Retention = (New-TimeSpan -Start [datetime]::parseexact($DateIn ... ~~~~~~~~~~~~~~~~~~~~~~ CategoryInfo : InvalidArgument: (:) [New-TimeSpan], ParameterBindingException FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.NewTimeSpanCommand
I changed the start conversion multiple times with
- [datetime]DateInName
- [datetime]::parseexact($DateInName, 'dd-MMM-yyyy', $null)
- changed the '-' into '/'.
But still the automation account fails. Is there something I missed when creating the runbook like inscript, is there a model I forgot to install ?
CodePudding user response:
As requested, here my comment as answer
The date format in $DateInName
shows it is formatted as 'dd-MM-yyyy'
(2-digit Day, 2-digit Month, 4digit Year).
Either do
$DateInName = [datetime]::ParseExact('24-05-2022', 'dd-MM-yyyy', $null)
$Retention = (New-TimeSpan -Start $DateInName -End (get-date)).Days
Or, if you want to perform this conversion inside the New-TimeSpan call, wrap it in brackets (..)
:
$DateInName = '24-05-2022'
$Retention = (New-TimeSpan -Start ([datetime]::ParseExact($DateInName, 'dd-MM-yyyy', $null)) -End (Get-Date)).Days