最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

windows - Unexpected space character inserted by variable - Stack Overflow

programmeradmin2浏览0评论

My time server (router) is 192.168.8.1. To update a Windows box's time:

net time \\192.168.8.1 /set /y

The goal is to implement the command with a variable in a .bat file:

set "ip="
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "Default"') do if not defined ip set ip=%%b
net time \\%ip% /set /y

Why does the script implement a space between \ and the 192.168.8.1:

net time \\ 192.168.8.1 /set /y

How to remedy?

If the variable as it is has a space, how is it "clipped" off?

My time server (router) is 192.168.8.1. To update a Windows box's time:

net time \\192.168.8.1 /set /y

The goal is to implement the command with a variable in a .bat file:

set "ip="
for /f "tokens=1-2 delims=:" %%a in ('ipconfig^|find "Default"') do if not defined ip set ip=%%b
net time \\%ip% /set /y

Why does the script implement a space between \ and the 192.168.8.1:

net time \\ 192.168.8.1 /set /y

How to remedy?

If the variable as it is has a space, how is it "clipped" off?

Share Improve this question edited Feb 7 at 6:55 Mofi 49.1k19 gold badges87 silver badges153 bronze badges asked Feb 7 at 3:44 gatorbackgatorback 1,5375 gold badges23 silver badges47 bronze badges 3
  • Is there a reason you're choosing to synchronize the time manually (albeit via a batch file) instead of just telling windows to sync automatically? – Damien_The_Unbeliever Commented Feb 7 at 6:52
  • 1 Modify the for /f line to: for /F "tokens=2 delims=:" %%G in ('%SystemRoot%\System32\ipconfig.exe ^| %SystemRoot%\System32\find.exe "Default"') do if not defined ip for /F %%H in ("%%G") do set "ip=%%H" Open a command prompt window, run for /? and read the output usage help carefully and completely from top of first to bottom of last page. It looks like you are using for /F without knowing what all the options like tokens= and delims= really mean. There is a space after Default Gateway . . . . . . . . . :. The delimiter of first for /F is just :. The space after : is kept! – Mofi Commented Feb 7 at 7:01
  • 1 You should not use a batch file to synchronize time. It is possible to configure the Windows Time service to synchronize time with a specific time server automatically. See the Microsoft documentation page: Windows Time service tools and settings – Mofi Commented Feb 7 at 7:04
Add a comment  | 

1 Answer 1

Reset to default 0

The space is appearing because the ipconfig line contains a space after the colon, so it is included in the value set into the variable.

Simplest solution afaics is

net time \\%ip:* =% /set /y

which should remove all characters in ip up to, and including, the first space (the character between the * and = and replacing that string with nothing (the string abetween the = and the %)

发布评论

评论列表(0)

  1. 暂无评论