我可以格式化Get-Date cmdlet这样没有问题:
$date = Get-Date -format "yyyyMMdd"
但是,一旦我在变量中获得了日期,我该如何格式化它呢?下面的声明
$dateStr = $date -format "yyyMMdd"
返回以下错误:
“你必须提供价值表达 在-f的右边 运营商”
我可以格式化Get-Date cmdlet这样没有问题:
$date = Get-Date -format "yyyyMMdd"
但是,一旦我在变量中获得了日期,我该如何格式化它呢?下面的声明
$dateStr = $date -format "yyyMMdd"
返回以下错误:
“你必须提供价值表达 在-f的右边 运营商”
当前回答
我需要时间和稍微改变一下格式。这对我的目的很有效:
$((get-date).ToLocalTime()).ToString("yyyy-MM-dd HHmmss")
2019-08-16 215757
根据评论中的@mklement0,这应该会产生相同的结果:
(get-date).ToString("yyyy-MM-dd HHmmss")
其他回答
根据输出需要格式化日期和时间
如果要格式化日期并将字符串分配给变量。 我结合了PowerShell和. net来提供灵活性。
$oDate = '{0}' -f ([system.string]::format('{0:yyyyMMddHHmmss}',(Get-Date)))
这是如何工作的
PowerShell Operator - '{0}' -f (.....) .NET表示法- [system.string]::format('customformat',InputObject) 结合PowerShell和。net的自定义格式- '{0:yyyyMMddHHmmss}' PowerShell提供的输入对象cmdlet (Get-Date) 存储在PowerShell变量- $oDate中
例子
如果运行的日期和时间是2021年7月5日星期一5:45:22 PM(格式“{0:F}”)。
$oDate = 20210705174522
使用代码
您可以通过使用Microsoft . net自定义日期时间符号修改'yyyMMddHHmmss'来定制字符串以满足您的要求。
一个非常方便的——但可能不是非常有效的——解决方案是使用成员函数GetDateTimeFormats(),
$d = Get-Date
$d.GetDateTimeFormats()
这将输出date-value的格式化样式的大型字符串数组。然后,您可以通过[]-操作符选择数组中的一个元素,例如,
PS C:\> $d.GetDateTimeFormats()[12]
Dienstag, 29. November 2016 19.14
一个简单而又好的方法是:
$time = (Get-Date).ToString("yyyy:MM:dd")
你可以用它来选择你想要的格式,然后在任何需要的地方跳过它。
$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."
对于任何试图格式化当前日期以用于HTTP报头的人,请使用“r”格式(RFC1123的缩写),但请注意警告…
PS C:\Users\Me> (get-date).toString("r")
Thu, 16 May 2019 09:20:13 GMT
PS C:\Users\Me> get-date -format r
Thu, 16 May 2019 09:21:01 GMT
PS C:\Users\Me> (get-date).ToUniversalTime().toString("r")
Thu, 16 May 2019 16:21:37 GMT
例如,不要忘记使用“tuniversal()”