datetimepowershell

Powershell showing old time after changing the time zone


Here's my powershell script:

$time = (Get-Date).ToShortTimeString()
Write-Host "Current Time: "$time
$destzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time")
$desttime = [System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversalTime(), $destzone)
$desttime = $desttime.ToShortTimeString()
Write-Host "UTC-6 = "$desttime
$newtime = (Get-Date).ToShortTimeString()
Write-Host "Current Time: "$newtime
if($newtime -eq $desttime)
{
Write-Host "ok"
}else
{
C:\Windows\System32\tzutil.exe /s "Central Standard Time"
}

What I am trying to achieve is that

  1. Get current system time
  2. Compare it with the Universal Time (utc-6)
  3. If it's the same then there is nothing to be done. If not, change system time zone to utc-6

Everything works, but once after setting the system time zone to utc-6, when I checks the current system time, it shows me the old time itself (though I can see that the system time zone has changed)

Looks like something like caching. Is there anything like that? Or Is there anything wrong with my script?

Can someone please lead me through a good way?


Solution

  • It's not your script's fault. Powershell only reads the time zone when the session is created.

    Get-Date and .Net methods like [System.TimeZoneInfo]::Local "cache" this, so the easiest solution is closing the window and starting a new Powershell session. Starting a new local session and importing it also "solves" the problem, but is rather clunky.

    WMI Objects are not subject to the same "cache" issue. Consider this as an option:

    $curzone = (Get-WMIObject –Class Win32_TimeZone).Caption
    $destzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time").DisplayName
    if($curzone -eq $destzone)
    {
    Write-Host "Current Time Zone already set to:"$curzone
    }else
    {
    C:\Windows\System32\tzutil.exe /s "Central Standard Time"
    $newcurzone = (Get-WMIObject –Class Win32_TimeZone).Caption
    Write-Host "Time Zone updated to:"$newcurzone
    }
    

    P.S. In case they fix this later, this currently is reproducible up to Windows 10 tech preview 2 with Powershell 5.0