问题
I was creating a project in which I needed to change the timezone to UTC so that tests run considering the timezone UTC only. So I have created this batch code:
FOR /F "tokens=* USEBACKQ" %%F IN (`tzutil /g`) DO SET PREVIOUS_TZ=%%F
tzutil /s "UTC"
cmd.exe /c npm run test:unit:base
tzutil /s "%PREVIOUS_TZ%"
I wonder how is it possible to return the previous timezone from UTC after the completion of tests. I found out that we can use "posttest" to hook the completion of tests. Thus, again how can we return the previous timezone with batch script?
回答1:
It seems that you already had UTC
which was set with your initial test and it was inherited.. anyway, I would rather do something like this.
I would use delims=
instead of tokens=*
Setting of variables is best done by closing them in double quotes starting at the beginning of the property, to the end of its value. i.e set "PREVIOUS_TZ=%%f"
I amended the variable names to better suit my feel.
@echo off
for /F "delims=" %%f in ('tzutil /g') do set "oldtz=%%f"
tzutil /s "UTC"
cmd.exe /c npm run test:unit:base
tzutil /s "%oldtz%"
for /F "delims=" %%a in ('tzutil /g') do if not "%oldtz%" == "%%a" (
echo Old timezone of "%oldtz%" was not set successfully. It is still %%a
)
pause
This should set it perfectly fine each time, but in the event it does not, it will tell you about it.
回答2:
I would offer this methodology:
@Echo Off
Rem Enter your required interim timezone below here.
Set "Interim_TZ=UTC"
Rem The next four non remarked lines determine,
Rem whether your current timezone requires changing to the interim one,
Rem and defines a variable containing your current one, if it does.
Set "Initial_TZ="
For /F "Delims=" %%G In (
'""%__AppDir__%tzutil.exe" /G | "%__AppDir__%findstr.exe" /VXC:"%Interim_TZ%""'
) Do Set "Initial_TZ=%%G"
Rem The below line will change the timezone, if it is not currently the interim one.
If Defined Initial_TZ "%__AppDir__%tzutil.exe" /S "%Interim_TZ%"
Rem Your commands using the interim timezone go below here.
Call "%ProgramFiles%\nodejs\npm.cmd" run test:unit:base
Rem If your initial timezone was different from the interim one,
Rem and you no longer need it assigned to the interim one,
Rem the next non remarked line changes it back again.
If Defined Initial_TZ "%__AppDir__%tzutil.exe" /S "%Initial_TZ%"
The idea is that it checks your current timezone, and if it is not already UTC
it sets a variable containing that timezone. The timezone is then only changed and reverted if there was a need to. I have additionally used Call
to invoke the npm
command in the same window as your running script. If I have guessed its path incorrectly, please change it as needed.
来源:https://stackoverflow.com/questions/60167366/how-is-it-possible-to-return-back-the-changed-timezone-after-the-completion-of-t