Display current time with time zone in PowerShell

前端 未结 7 809
盖世英雄少女心
盖世英雄少女心 2021-02-14 02:06

I\'m trying to display the local time on my system with the TimeZone. How can I display time in this format the simplest way possible on any system?:

Time: 8:00:34 AM ES

相关标签:
7条回答
  • 2021-02-14 02:44

    I'm not aware of any object that can do the work for you. You could wrap the logic in a function:

    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
    

    Or even take the initials of the time zone id:

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

    You should look into DateTime format strings. Although I'm not sure they can return a time zone short name, you can easily get an offset from UTC.

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

    This returns:

    8:00:34 AM -04:00
    
    0 讨论(0)
  • 2021-02-14 02:50

    Be loath to define another datetime format! Use an existing one, such as RFC 1123. There's even a PowerShell shortcut!

    Get-Date -format r
    

    Thu, 14 Jun 2012 16:44:18 GMT

    Ref.: Get-Date

    0 讨论(0)
  • 2021-02-14 02:51

    This is a better answer:

    $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()
    

    Output: 3/20/2017 11:55:55 PM

    0 讨论(0)
  • 2021-02-14 02:51

    I just combined several scripts and finally was able to run the script in my domain controller.

    The script provides the output of time and timezone for all the machines connected under the domain. We had a major issue with our application servers and used this script to cross check the time and timezone.

    # 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
    
    0 讨论(0)
  • 2021-02-14 02:57

    While this is a bit ... naive perhaps, it's one way to get an abbreviation without a switch statement:

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

    My regular expression probably leaves something to be desired.

    The output of the above for my time zone is EST. I did some looking as I wanted to see what the value would be for other GMT offset settings, but .NET doesn't seem to have very good links between DateTime and TimeZoneInfo, so I couldn't just programmatically run through them all to check. This might not work properly for some of the strings that come back for StandardName.

    EDIT: I did some more investigation changing the time zone on my computer manually to check this and a TimeZoneInfo for GMT+12 looks like this:

    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
    

    Which produces this result for my code:

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

    So, I guess you'd have to detect whether the StandardName appears to be a set of words or just offset designation because there's no standard name for it.

    The less problematic ones outside the US appear to follow the three-word format:

    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
    
    0 讨论(0)
提交回复
热议问题