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
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?
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