在 Azure 自动化帐户 (powershell) 中将字符串转换为日期时间

Convert string to datetime in Azure automation Account (powershell)

我正在尝试获取字符串日期时间和当前日期之间的天数差异。我在本地 PC 上尝试了以下代码

$Dateinname = "24-05-2022"
$Retention = (New-TimeSpan -Start $DateInName -End (get-date)).Days

        if ($Retention -gt 14){
           //do something
         }

但是在自动化帐户 'Powershell script' 中,相同的代码提供了以下错误:

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

我用

多次更改了开始转换
  1. [日期时间]DateInName
  2. [日期时间]::parseexact($DateInName, 'dd-MMM-yyyy', $null)
  3. 将“-”更改为“/”。

但自动化帐户仍然失败。 在创建像 inscript 这样的 runbook 时,我是否遗漏了什么,是否有我忘记安装的模型?

应要求,这里是我的评论作为回答

$DateInName 中的日期格式显示其格式为 'dd-MM-yyyy'
(2 位数日,2 位数月份,4 位数年份)。

要么

$DateInName = [datetime]::ParseExact('24-05-2022', 'dd-MM-yyyy', $null)
$Retention = (New-TimeSpan -Start $DateInName -End (get-date)).Days

或者,如果您想在 New-TimeSpan 调用中执行此转换,请将其括在方括号 (..):

$DateInName = '24-05-2022'
$Retention = (New-TimeSpan -Start ([datetime]::ParseExact($DateInName, 'dd-MM-yyyy', $null)) -End (Get-Date)).Days