簡體   English   中英

在 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 腳本”中,相同的代碼提供了以下錯誤:

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. [日期時間]日期名稱
  2. [日期時間]::parseexact($DateInName, 'dd-MMM-yyyy', $null)
  3. 將“-”更改為“/”。

但自動化帳戶仍然失敗。 在創建像 inscript 這樣的 runbook 時,我是否遺漏了什么,是否有一個 model 我忘記安裝了?

根據要求,這里我的評論作為答案

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM