Created
April 23, 2021 12:25
-
-
Save MovGP0/0858d4d02d5f366886f5d5ac88cfb125 to your computer and use it in GitHub Desktop.
Get the time from an NTP server
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
function Get-InternetTime | |
{ | |
param($NtpServer = 'time.windows.com') | |
try | |
{ | |
$address = [Net.Dns]::GetHostEntry($NtpServer).AddressList[0]; | |
} | |
catch | |
{ | |
Write-Host "Could not resolve IP address from '" + $NtpServer + "'.", "ntpServer"; | |
return; | |
} | |
$ep = New-Object Net.IPEndPoint($address, 123); | |
$s = New-Object Net.Sockets.Socket( | |
[Net.Sockets.AddressFamily]::InterNetwork, | |
[Net.Sockets.SocketType]::Dgram, | |
[Net.Sockets.ProtocolType]::Udp); | |
try | |
{ | |
$s.Connect($ep); | |
$buffer = New-Object byte[] 48 ; | |
$buffer[0] = '0X1B'; | |
[Void]$s.Send($buffer); | |
[Void]$s.Receive($buffer); | |
$offsetTransmitTime = 40; | |
$intpart = 0; | |
$fractpart = 0; | |
for ($i = 0; $i -le 3; $i++) | |
{ | |
$intpart = 256 * $intpart + $buffer[$offsetTransmitTime + $i] | |
} | |
for ($i = 4; $i -le 7; $i++) | |
{ | |
$fractpart = 256 * $fractpart + $buffer[$offsetTransmitTime + $i]; | |
} | |
$milliseconds = $intpart * 1000 + ($fractpart * 1000) / 0x100000000L; | |
} | |
finally | |
{ | |
$s.Close(); | |
} | |
$timeSpan = [TimeSpan]::FromTicks($milliseconds * [TimeSpan]::TicksPerMillisecond); | |
$dateTime = New-Object DateTime(1900, 1, 1); | |
$dateTime += $timeSpan; | |
$offsetAmount = [TimeZone]::CurrentTimeZone.GetUtcOffset($dateTime); | |
$networkDateTime = $dateTime + $offsetAmount; | |
return $networkDateTime; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment