【问题标题】:Date formatted using ToString() with a custom format results in inconsistent output使用自定义格式的 ToString() 格式化的日期会导致输出不一致
【发布时间】:2022-01-25 07:57:59
【问题描述】:

我使用 powershell 脚本导出所有存在的 DHCP 服务器的列表以及服务器上的范围。结果必须在 python 的第二个脚本中解析。 (这是我们监控的系统)。

这是脚本:

$DHCPServers = (Get-DhcpServerInDC).Dnsname
$Scopes = @()
$Leases = @()
foreach ($DHCPServer in $DHCPServers) {
    $Scopes += Get-DhcpServerv4Scope -ComputerName $DHCPServer | select-Object @{Name="DHCPServer"; Expression = {$DHCPServer}},ScopeID,Name,StartRange,EndRange
}

$Scopes | Export-Csv -path .\DHCP_Freeleases-Scopes-get.csv -Encoding utf8 -NoTypeInformation

foreach ($Scope in $Scopes) {
    $Leases += Get-DHCPServerv4Lease -ScopeId $Scope.ScopeID -ComputerName $Scope.DHCPServer | select-Object @{Name="DHCPServer"; Expression = {$Scope.DHCPServer}}, IPAddress, @{Name="LeaseExpiryTime"; Expression = {$_.LeaseExpiryTime.toString("yyyy/MM/dd/HH:mm")}}, @{Name="ScopeID"; Expression = {$Scope.ScopeID}}, Addressstate
}

$Leases | Export-Csv -path .\DHCP_Freeleases-Leases-get.csv -Encoding utf8 -NoTypeInformation

当我在本地 DHCP 服务器 (Windows Server 2012 R2) 上编写该脚本时,CSV 导出是我想要的方式:

"dhcp1.server.intern","10.26.9.202","2022/01/25/08:22","172.26.9.192","Active"

现在我将脚本部署到不同的服务器(Windows Server 2019),完全相同的脚本给了我这个 CSVline:

"dhcp1.server.intern","10.26.9.202","2022.01.25.08:22","172.26.9.192","Active"

我想了解它:这怎么可能?我以为 .toString() 会用我的参数给出它?

感谢您的帮助!

【问题讨论】:

  • 我想您是在谈论更改的日期分隔符?如果是这样,那通常是一种文化背景。如果不是……请更具体地说明您在说什么。 [咧嘴]
  • 是的,我输入了分隔符。谢谢你,我没有想出这个词来做我的研究????
  • 我看到你有一个适合你的答案。 很高兴知道! [咧嘴一笑]

标签: powershell csv datetime date-formatting


【解决方案1】:

DateTime.ToString() 方法将正斜杠和冒号视为格式说明符。这意味着它们可以被特定于语言环境的字符替换。

来自documentation:

“d”、“f”、“F”、“g”、“h”、“H”、“K”、“m”、“M”、“s”、“t”、“y” ", "z", 格式字符串中的“:”或“/”字符被解释为自定义 格式说明符而不是文字字符。为了防止一个 字符被解释为格式说明符,您可以 在它前面加上一个反斜杠 (),它是转义字符。

要强制使用固定格式,只需用反斜杠转义这些字符:

$_.LeaseExpiryTime.toString("yyyy\/MM\/dd\/HH\:mm")

正如您在 cmets 中所指出的,您也可以使用 predefined format,例如“s”(ISO 8601),根据定义,它与区域设置无关:

$_.LeaseExpiryTime.toString('s')

输出看起来像2022-01-25T11:20:26。

【讨论】:

  • 感谢您的回答!我先试过了,效果很好。阅读文档也向我展示了我可以编写一个简单的s 并返回 ISO 格式。现在我用那个。再次感谢! :)
  • @Gamienator 好点,我已将其添加到我的答案中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
相关资源
最近更新 更多