powershellwinpe

How to sync the clock in WinPE


Ran into an issue where I need to call an Internet API within a running WinPE image that could be on a local VM or on a physical machine where I can't trust the local clock. The API requires that the local clock be correct within some threshold, or the https certificate will not validate.

The WinPE image does not have w32tm.exe or proper support for timezones that use Daylight Savings Time/Summer time. Most Internet resources rely on w32tm for this.

What is a simple, but good way to get the clock to be correct, preferably using Powershell 5.1? Network access and an elevated prompt can be assumed.


Solution

  • As I was unable to find a good resource for this, at first, I looked at how to manually call an NTP server from Powershell. But I happened upon an even simpler answer that I thought might be useful to others--just utilize the Date header from a normal web HTTP request. This will not be uber-reliable if there is a network issue, but then my other calls would fail anyway, so it should be fine.

    Set the timezone of the image to UTC, e.g., via DISM:

    Invoke-Process -FilePath Dism -ArgumentList "/Image:$MountDir /Set-TimeZone:`"UTC`""
    

    Use a script inside the booted image to sync the local clock using Google's Date header, which returns the datetime in GMT. The format is currently compatible with PS's Set-Date command.

    Set-Date -Date "$((Invoke-WebRequest -UseBasicParsing "http://google.com/").Headers.Date)"