Last active
July 25, 2020 03:57
-
-
Save ooltcloud/c780872fbbe5248bb782ef9b0401e8d2 to your computer and use it in GitHub Desktop.
GPS を使った簡易時刻合わせ
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-------------- | |
# GPS を使った簡易時刻合わせ (管理者権限で実行) | |
#-------------- | |
function SetDateFromGPS($portname) { | |
trap{ | |
# エラーが発生したら終了 | |
break | |
} | |
# GPS の COM ポートを Open | |
$port = New-Object System.IO.Ports.SerialPort | |
$port.PortName = $portname | |
$port.Open() | |
$port.ReadTimeout = 3000 # タイムアウト = 3秒 | |
while ($true) { | |
$line = $port.ReadLine() # 一行読み込み | |
$elem = $line -split "," # CSV の分解set | |
$cmd = $elem[0] # コマンド | |
if ($cmd -eq '$GPRMC') { | |
$state = $elem[2] # A:有効 V:警告 | |
$utcdate = $elem[9] # 日付 (UTC) | |
$utctime = $elem[1] # 時刻 (UTC) | |
if ($utcdate -ne '' -and $utctime -ne '') { | |
# 受信時刻の解析 | |
$year = [int]($utcdate.Substring(4,2)) + 2000 # 20yy | |
$month = [int]($utcdate.Substring(2,2)) | |
$day = [int]($utcdate.Substring(0,2)) | |
$hour = [int]($utctime.Substring(0,2)) | |
$min = [int]($utctime.Substring(2,2)) | |
$sec = [int]($utctime.Substring(4,2)) | |
$ms = [int]([decimal]($utctime.Substring(6)) * 1000) # .00 × 1000 = ms | |
$datetime = New-Object DateTime($year, $month, $day, $hour, $min, $sec, $ms, [DateTimeKind]::Utc) | |
# 時刻設定 | |
Set-Date -Date $datetime.ToLocalTime() | |
Write-Host $line | |
Write-Host "時刻を設定しました" | |
break | |
} else { | |
Write-Host "No Data" | |
Write-Host $line | |
} | |
} | |
} | |
$port.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使い方
管理者権限で SetDateFromGPS COMxx を実行。
実行例 (COM4の場合)