Datetime Powershell在更改时区后显示旧时间

Datetime Powershell在更改时区后显示旧时间,datetime,powershell,Datetime,Powershell,以下是我的powershell脚本: $time = (Get-Date).ToShortTimeString() Write-Host "Current Time: "$time $destzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("Central Standard Time") $desttime = [System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversal

以下是我的powershell脚本:

$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"
}
我想要达到的是

  • 获取当前系统时间
  • 将其与世界时(utc-6)进行比较
  • 如果是一样的话,那就没什么可做的了。如果不是,请将系统时区更改为utc-6
  • 一切正常,但一旦将系统时区设置为utc-6,当我检查当前系统时间时,它会显示旧时间本身(尽管我可以看到系统时区已更改)

    看起来有点像缓存。有类似的吗?还是我的剧本有什么问题


    有人能带我走一条好路吗?

    这不是你剧本的错。Powershell仅在创建会话时读取时区

    Get Date
    和.Net方法,如
    [System.TimeZoneInfo]::Local
    “缓存”此,因此最简单的解决方案是关闭窗口并启动新的Powershell会话。启动一个新的本地会话并导入它也“解决”了这个问题,但是相当笨拙

    WMI对象不存在相同的“缓存”问题。 认为这是一个选项:

    $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
    }
    

    另外,如果他们以后解决了这一问题,这一点目前可以复制到Windows 10 tech preview 2和Powershell 5.0。出于好奇,时区更改后创建的新Powershell会话是否反映了更改?谢谢。因为这对我来说是个紧急情况,所以我只是检查了一下时区,然后就成功了。