2012-06-14 100 views
10

我試圖顯示我的系統與時區的本地時間。我怎麼能以這種格式顯示時間的最簡單的方法可能任何系統:有關將Powershell顯示當前時區與時區

時間:上午08時零零分34秒EST

我目前使用下面的腳本:

$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 

我希望能夠在不依賴簡單邏輯的情況下顯示時間,但能夠在任何系統上給出本地時區。謝謝!

回答

9

雖然這是一個有點天真......也許,這是獲得一個一種方式沒有開關聲明的縮寫:

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

我的regu年輕的表情可能會讓人有些不滿。

上述我的時區輸出爲EST。我做了一些看,因爲我想看看其他GMT偏移設置的值是什麼,但.NET在DateTimeTimeZoneInfo之間似乎沒有很好的鏈接,所以我不能通過編程方式通過它們全部檢查。對於返回StandardName的某些字符串,這可能無法正常工作。

編輯:我做了一些更多的研究改變了我的計算機上的時區手動檢查這個和TimeZoneInfoGMT+12看起來是這樣的:

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 
+0

工程就像一個美麗! –

+0

@Ken我有點尷尬,但我很高興它做到了這一招:)。 – Shibumi

+1

'SA太平洋標準時間'變成'SPST';這並不準確。您提供的信息非常有幫助。我決定只是爲了獲得分鐘抵消: '[System.TimeZone] :: CurrentTimeZone.GetUtcOffset([datetime] :: Now).TotalMinutes' – VertigoRay

1

我不知道任何可以爲你工作的物體。你可以換邏輯的功能:

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) 
+0

記得撥打'IsDaylightSavingTime'檢查是否看'標準名稱'(我認爲這與'Id'相同,但不清楚,如果總是如此)或DaylightName屬性。您還需要處理所有其他時區的默認情況。 – Richard

+0

@Richard默認情況下有什麼問題? –

+0

沒有一個。 – Richard

6

你應該看看DateTime format strings。儘管我不確定他們能否返回時區短名稱,但您可以輕鬆獲得UTC的偏移量。

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

這將返回:

8:00:34 AM -04:00 
+0

我欣賞格式化的幫助。但是,我仍然需要找出將時區關聯的方法。 –

3

要厭惡定義另一個日期時間格式!使用現有的,如rfc 1123。甚至有一個Powershell快捷鍵!

get-Date -format r 

星期四,2012 6月14日16點44分18秒GMT

http://technet.microsoft.com/en-us/library/hh849887.aspx

+5

需要注意的是,這不是很準確:目前報道的是格林威治標準時間(格林尼治標準時間前1小時)。 – Richard

+0

但這不正確,因爲當前時區不是GMT。我以前使用格式,但它總是給出GMT而不是正確的時區。 –

+6

無論你的時區是什麼時區,它都會得到GMT,它是硬編碼的 - (Get-Culture).DateTimeFormat.RFC1123Pattern, –

0

就聯合幾個腳本終於能夠在我的域控制器上運行該腳本。腳本爲域下連接的所有機器提供時間和時區的輸出。 我們在應用程序服務器上遇到了一個主要問題,並使用此腳本來檢查時間和時區。

  #Below Scripts provides the Time and TimeZone 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 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 Not reachable from ping `n") 
         } 

      } 

      Stop-Transcript 
0

這是一個更好的答案:

$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秒