【问题标题】:Display current time with time zone in PowerShell在 PowerShell 中显示当前时间和时区
【发布时间】:2012-06-17 15:38:43
【问题描述】:

我正在尝试使用 TimeZone 在我的系统上显示本地时间。如何在任何系统上以这种最简单的方式显示时间?:

时间:美国东部标准时间上午 8:00:34

我目前正在使用以下脚本:

$localtz = [System.TimeZoneInfo]::Local | Select-Object -expandproperty Id
if ($localtz -match "Eastern") {$x = " EST"}
if ($localtz -match "Pacific") {$x = " PST"}
if ($localtz -match "Central") {$x = " CST"}
"Time: " + (Get-Date).Hour + ":" + (Get-Date).Minute + ":" + (Get-Date).Second + $x

我希望能够在不依赖简单逻辑的情况下显示时间,但能够在任何系统上提供本地时区。

【问题讨论】:

  • 请注意,包含“Eastern”一词的时区名称不止一个,因此像这样的简单匹配会中断。例如,有“SA 东部标准时间”和“AUS 东部标准时间”。

标签: powershell time timezone


【解决方案1】:

虽然这有点……可能很天真,但这是在没有 switch 语句的情况下获得 an 缩写的一种方法:

[Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])\w+\s*', '$1')

我的正则表达式可能还有一些不足之处。

上面我的时区的输出是EST。我做了一些查看,因为我想看看其他 GMT 偏移设置的值是多少,但是 .NET 在DateTimeTimeZoneInfo 之间似乎没有很好的链接,所以我不能只是以编程方式运行他们都来检查。对于为StandardName 返回的某些字符串,这可能无法正常工作。

编辑:我进行了更多调查,手动更改计算机上的时区以检查这一点,GMT+12TimeZoneInfo 看起来像这样:

PS> [TimeZoneInfo]::Local

Id                         : UTC+12
DisplayName                : (GMT+12:00) Coordinated Universal Time+12
StandardName               : UTC+12
DaylightName               : UTC+12
BaseUtcOffset              : 12:00:00
SupportsDaylightSavingTime : False

这会为我的代码产生这个结果:

PS> [Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])\w+\s*', '$1')
U+12

所以,我想您必须检测 StandardName 是否看起来是一组单词或只是偏移指定,因为它没有标准名称。

美国以外的问题较少的似乎遵循三字格式:

PS> [TimeZoneInfo]::Local

Id                         : Tokyo Standard Time
DisplayName                : (GMT+09:00) Osaka, Sapporo, Tokyo
StandardName               : Tokyo Standard Time
DaylightName               : Tokyo Daylight Time
BaseUtcOffset              : 09:00:00
SupportsDaylightSavingTime : False

PS> [Regex]::Replace([System.TimeZoneInfo]::Local.StandardName, '([A-Z])\w+\s*', '$1')
TST

【讨论】:

  • @Ken 我对此有点尴尬,但我很高兴它成功了 :)。
  • SA Pacific Standard Time 变为 SPST;这并不准确。不过,您提供的信息非常有帮助。我决定只解决分钟偏移量:[System.TimeZone]::CurrentTimeZone.GetUtcOffset([datetime]::Now).TotalMinutes
【解决方案2】:

您应该查看DateTime format strings。虽然我不确定他们是否可以返回时区短名称,但您可以轻松获得与 UTC 的偏移量。

$formatteddate = "{0:h:mm:ss tt zzz}" -f (get-date)

这会返回:

8:00:34 AM -04:00

【讨论】:

  • 感谢格式化方面的帮助。但是,我仍然需要想办法关联时区。
【解决方案3】:

不愿定义另一种日期时间格式!使用现有的,例如RFC 1123。甚至还有一个 PowerShell 快捷方式!

Get-Date -format r

格林威治标准时间 2012 年 6 月 14 日星期四 16:44:18

参考:Get-Date

【讨论】:

  • 应该注意这不是很准确:当前报告GMT,实际上是BST(比格林威治标准时间提前一小时)。
  • 但这不正确,因为当前时区不是 GMT。我以前使用过格式,但它总是给出 GMT 而不是正确的时区。
  • 无论您的时区如何,您都会获得 GMT,它是硬编码的 - (Get-Culture).DateTimeFormat.RFC1123Pattern,
  • -format u 为您提供正确的通用时间,'-g' API 已损坏 IMO
【解决方案4】:

这是一个更好的答案:

$A = Get-Date                    #Returns local date/time
$B = $A.ToUniversalTime()        #Convert it to UTC

# Figure out your current offset from UTC
$Offset = [TimeZoneInfo]::Local | Select BaseUtcOffset   

#Add the Offset
$C = $B + $Offset.BaseUtcOffset
$C.ToString()

输出: 2017 年 3 月 20 日晚上 11:55:55

【讨论】:

    【解决方案5】:

    我不知道有任何对象可以为您完成这项工作。您可以将逻辑包装在一个函数中:

    function Get-MyDate{
    
        $tz = switch -regex ([System.TimeZoneInfo]::Local.Id){
            Eastern    {'EST'; break}
            Pacific    {'PST'; break}
            Central    {'CST'; break}
        }
    
        "Time: {0:T} $tz" -f (Get-Date)
    }
    
    Get-MyDate
    

    或者甚至取时区id的首字母:

    $tz = -join ([System.TimeZoneInfo]::Local.Id.Split() | Foreach-Object {$_[0]})
    "Time: {0:T} $tz" -f (Get-Date)
    

    【讨论】:

    • 记得调用IsDaylightSavingTime来检查是否查看StandardName(我认为这与Id相同,但不清楚是否始终为真)或DaylightName属性。您还需要处理所有其他时区的默认情况。
    • 知道了,没什么大不了的,在这种情况下,你会得到时间(除非你想打印一个默认值):)
    【解决方案6】:

    我只是组合了几个脚本,终于能够在我的域控制器中运行脚本。

    该脚本为域下连接的所有机器提供时间和时区的输出。 我们的应用程序服务器出现了一个重大问题,并使用此脚本来交叉检查时间和时区。

    # The below scripts provides the time and time zone for the connected machines in a domain
    # Appends the output to a text file with the time stamp
    # Checks if the host is reachable or not via a ping command
    
    Start-Transcript -path C:\output.txt -append
    $ldapSearcher = New-Object directoryservices.directorysearcher;
    $ldapSearcher.filter = "(objectclass=computer)";
    $computers = $ldapSearcher.findall();
    
    foreach ($computer in $computers)
    {
        $compname = $computer.properties["name"]
        $ping = gwmi win32_pingstatus -f "Address = '$compname'"
        $compname
        if ($ping.statuscode -eq 0)
        {
            try
            {
                $ErrorActionPreference = "Stop"
                Write-Host “Attempting to determine timezone information for $compname…”
                $Timezone = Get-WMIObject -class Win32_TimeZone -ComputerName $compname
    
                $remoteOSInfo = gwmi win32_OperatingSystem -computername $compname
                [datetime]$remoteDateTime = $remoteOSInfo.convertToDatetime($remoteOSInfo.LocalDateTime)
    
                if ($Timezone)
                {
                    foreach ($item in $Timezone)
                    {
                        $TZDescription  = $Timezone.Description
                        $TZDaylightTime = $Timezone.DaylightName
                        $TZStandardTime = $Timezone.StandardName
                        $TZStandardTime = $Timezone.StandardTime
                    }
                    Write-Host "Timezone is set to $TZDescription`nTime and Date is $remoteDateTime`n**********************`n"
                }
                else
                {
                    Write-Host ("Something went wrong")
                }
             }
             catch
             {
                 Write-Host ("You have insufficient rights to query the computer or the RPC server is not available.")
             }
             finally
             {
                 $ErrorActionPreference = "Continue"
             }
        }
        else
        {
            Write-Host ("Host $compname is not reachable from ping `n")
        }
    }
    
    Stop-Transcript
    

    【讨论】:

      【解决方案7】:

      俄罗斯、法国、挪威、德国:

      get-date -format "HH:mm:ss ddd dd'.'MM'.'yy' г.' zzz"
      

      俄罗斯时区的输出:22:47:27 Чт 21.11.19 г。 +03:00

      其他 - 只需更改代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-31
        • 2018-12-04
        • 2012-11-28
        • 2020-06-21
        相关资源
        最近更新 更多