Skip to content

Instantly share code, notes, and snippets.

@ooltcloud
Last active December 5, 2018 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ooltcloud/20e7d7551007370b4b8e345499d79cb3 to your computer and use it in GitHub Desktop.
Save ooltcloud/20e7d7551007370b4b8e345499d79cb3 to your computer and use it in GitHub Desktop.
Powershell と NICT 公開 NTP サービスを使用した簡易時刻同期 (http プロトコル使用)
# シリアル秒起点時刻
$epoch = New-Object System.Datetime @(1900, 1, 1, 9, 0, 0)
# 現在時刻取得 (「NICT 公開 NTP サービス」を利用)
$ntp = Invoke-WebRequest "https://ntp-a1.nict.go.jp/cgi-bin/ntp"
# 現在時刻のシリアル秒を取得
$xml = [xml]$ntp.Content
$val = [Double]($xml.HTML.BODY -replace "`n", "")
# 現在時刻を求める
$now = $epoch.AddSeconds($val)
Write-Host $now
# 時刻設定
Set-Date -Date $now
@ooltcloud
Copy link
Author

ooltcloud commented Nov 23, 2018

windows time サービス (w32time/w32tm) で同期したほうがよいのは確かですが、windows time サービスによる時刻同期の設定自体が難しくてどうしても時刻同期させられない場合とか、ntp のポート (port 123) が閉じられていて同期できない場合などで、ともかく精度は問わないし時刻も戻ってもいいから(急変していいから)手早く時刻を合わせたい、という場合を想定しています。要管理者権限です。また Invoke-WebRequest が必要なので Powershell 3.0 以上の環境が必要です。(つまり Windows 7 / 2008R2 では動かない場合があります。Powershell の Version は $PSVersionTable で知ることができます。)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment