0

So I'm trying to build a batch file that will either automatically toggle between 2 time zones; or take a user input and change the time zone accordingly

I tried to have a toggle system but I can't figure out how to store the current time zone based on tzutil /g or setup if statements correctly to identify which time zone to change to. I run it in admin mode so thats not the issue.

@echo off
echo The current time is:
tzutil /g
echo.
SET /p NewTimeZone="Enter the time zone you wish to change to: "
tzutil /s %NewTimeZone%

the first part works fine, it tell the user what time zone it's in and then asks to change it. however that last line is whats causing all the trouble, I can't seem to get it work, for example when I run the code, I type in: "Mountain Standard Time" which is the string its needs to change the time however it never goes through, it just closes the program and the time zone never changes

HAL9256
  • 12,384
  • 1
  • 34
  • 46
  • 2
    Have you tried putting quotes around the variable: `tzutil /s "%NewTimeZone%"` – HAL9256 Jun 10 '19 at 21:46
  • TBF, it's not uncommon for people not to expect, `Set /P Var="Prompt"` to actually replace, `Prompt` with `Input`. The recommended syntax is `Set /P "Var=Prompt"`, which may help you better see it better. – Compo Jun 10 '19 at 22:03
  • 1
    [How to store command output.](https://stackoverflow.com/questions/6359820/how-to-set-commands-output-as-a-variable-in-a-batch-file) – BDM Jun 10 '19 at 22:45
  • for the "troubleshooting" part: don't run per double click, open a `cmd` window and execute the script from there. It can also be very useful to run it with `echo off` – Stephan Jun 24 '22 at 18:14

2 Answers2

1

Usually you get a command's output with a for /f loop:

for /f "delims=" %%a in ('tzutil /g') do set "org=%%a"
echo original=%org%

You can also put it into a file (so it survives even a reboot):

>original.zone tzutil /g
type original.zone

and get it back with:

<original.zone set /p "org="
echo original=%org%

and set it back (with both methods):

tzutil /s "%org%"

You can verify the user's input like:

set /p "new=Enter new time zone: "
tzutil /l | findstr /ix "%new%"
if errorlevel 1 ( echo non-existing zone & goto :eof )
tzutil /s "%new%"
Stephan
  • 53,940
  • 10
  • 58
  • 91
0

You need to use:

tzutil /s "%NewTimeZone%"

In last line

Tyler2P
  • 2,324
  • 26
  • 22
  • 31