14

TimeZone を使用してシステムの現地時間を表示しようとしています。どのシステムでも可能な限り簡単な方法で、この形式で時間を表示するにはどうすればよいですか?:

時間: 午前 8:00: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

単純なロジックに頼らずに時刻を表示できるようにしたいのですが、どのシステムでもローカル タイムゾーンを指定できるようにしたいと考えています。

4

7 に答える 7

12

これは少し...ナイーブかもしれませんが、switchステートメントなしで略語を取得する1つの方法です:

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

私の正規表現には、おそらく何かが必要です。

私のタイムゾーンに対する上記の出力はEST. 他のGMTオフセット設定の値がどうなるかを確認したかったので、いくつか調べましたが、.NETは と の間にあまり良いリンクを持っていないようDateTimeですTimeZoneInfo。これは、 に返される一部の文字列では正しく機能しない場合がありますStandardName

編集:TimeZoneInfoこれを確認するために、コンピューターのタイムゾーンを手動で変更してさらに調査を行いました。これはGMT+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したがって、標準的な名前がないため、一連の単語のように見えるのか、単なるオフセット指定であるのかを検出する必要があると思います。

米国以外で問題の少ないものは、3 語形式に従っているようです。

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
于 2012-06-14T19:48:46.467 に答える
8

DateTimeフォーマット文字列を調べる必要があります。タイムゾーンの短い名前を返すことができるかどうかはわかりませんが、UTCからのオフセットを簡単に取得できます。

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

これは次を返します:

8:00:34 AM -04:00
于 2012-06-14T15:34:52.563 に答える
5

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

于 2012-06-14T15:45:32.463 に答える
2

これはより良い答えです:

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

于 2017-03-21T04:46:17.883 に答える
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)
于 2012-06-14T15:26:05.220 に答える
0

いくつかのスクリプトを組み合わせて、最終的にドメイン コントローラーでスクリプトを実行することができました。

このスクリプトは、ドメインに接続されているすべてのマシンの時刻とタイムゾーンの出力を提供します。アプリケーションサーバーに大きな問題があり、このスクリプトを使用して時間とタイムゾーンをクロスチェックしました.

# 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
于 2016-07-08T12:17:45.787 に答える