我可以格式化Get-Date cmdlet这样没有问题:

$date = Get-Date -format "yyyyMMdd"

但是,一旦我在变量中获得了日期,我该如何格式化它呢?下面的声明

$dateStr = $date -format "yyyMMdd"

返回以下错误:

“你必须提供价值表达 在-f的右边 运营商”


当前回答

你可以做的一件事是:

$date.ToString("yyyyMMdd")

其他回答

我需要时间和稍微改变一下格式。这对我的目的很有效:

$((get-date).ToLocalTime()).ToString("yyyy-MM-dd HHmmss")

2019-08-16 215757

根据评论中的@mklement0,这应该会产生相同的结果:

(get-date).ToString("yyyy-MM-dd HHmmss")

你可以做的一件事是:

$date.ToString("yyyyMMdd")

来自@stej的回答非常翔实,但这里是一个简短的回答: 在其他选项中,您有3个简单的选项来格式化[System. System.]存储在变量中的DateTime:

将变量传递给Get-Date cmdlet: 获取日期-格式“HH:mm”$date 使用toString()方法: date.ToString美元(“HH: mm”) 使用复合格式: "{0:HH:mm}" -f $date

你可以用它来选择你想要的格式,然后在任何需要的地方跳过它。

$DTFormats = (Get-Date).GetDateTimeFormats()
$Formats = @()
$i=0
While ($i -lt $DTFormats.Count){
    $row = [PSCustomObject]@{
        'IndexNumber' = $i
        'DateTime Format' = $DTFormats[$i]
    }
    $Formats += $row
    $i++
}

$DTSelection = ($Formats | Out-GridView -OutputMode Single -Title 'Select DateTime Format').IndexNumber
$MyDTFormat = "(Get-Date).GetDateTimeFormats()[$DTSelection]"
Write-Host " "
Write-Host " Use the following code snippet to get the DateTime format you selected:"
Write-Host "    $MyDTFormat" -ForegroundColor Green
Write-Host " "
$MyDTFormat | Clip
Write-Host " The code snippet has been copied to your clipboard. Paste snippet where needed."

和在。net中一样:

$DateStr = $Date.ToString("yyyyMMdd")

Or:

$DateStr = '{0:yyyyMMdd}' -f $Date