批处理脚本 - 等到网络建立

时间:2014-10-03 19:25:44

标签: windows batch-file active-directory network-programming mapped-drive

我有logon.bat脚本,每次用户登录到Active Directory域的工作站时都会运行。

此脚本使用以下命令映射某些网络驱动器:

net use x: \\192.168.0.2\share1
net use y: \\192.168.0.3\share2
net use z: \\192.168.0.4\share3

但是,对于某些工作站,此脚本在工作站本身完全建立自己的LAN连接之前运行。然后用户进入开始菜单>计算机,并查看每个映射驱动器的红色X.此时,网络已建立,因此如果他们点击红色X,它就会消失。不过,我希望logon.bat脚本在运行net-use命令之前验证网络是否已建立。

我已经看到过这样的解决方案,需要在组策略上更改设置,或者需要更改罪魁祸首工作站上的设置。但是,我对在我当前的批处理脚本中解决此问题的解决方案感兴趣(不需要在该脚本之外添加任何其他脚本依赖项)。

我已经看到其他脚本解决方案只是将超时(或睡眠)放入批处理脚本中,以便在运行net use命令之前等待一段任意时间。这些解决方案提供了等待常数,这些等待常数可以比驱动器映射驱动器稍晚一些映射"或者"仍然有可能在建立网络之前运行net-use命令"。

相反,我喜欢一个脚本,它会检查每一秒以查看网络是否已经建立,然后(成功时)继续运行" net use"先前提到的命令。

如何在Windows批处理脚本中实现此目的?

3 个答案:

答案 0 :(得分:5)

简单检查。持续一段时间后不会自动退出。为我需要的工作而努力。

:CHECKFOLDER
TIMEOUT 1
IF NOT EXIST C:\TEST GOTO CHECKFOLDER

答案 1 :(得分:4)

我在How to ping a server only once from within a batch file?Deleting Desktop Shortcuts Associated With Network Drives?上的答案包含有关此任务的有用信息。

以下是1台服务器的模板批处理脚本:

@echo off
set "Server=192.168.0.2"
set "RetryCount=0"

:CheckServer
rem Ping server only once with a time limit of 1000 ms.
%SystemRoot%\System32\ping.exe -n 1 -w 1000 %Server% >nul
if not errorlevel 1 goto MapDrive

rem Connection to server is not yet established. Give up after 30 seconds
rem in case of not being in right LAN or no network connection at all or
rem this server is currently not running.
set /A RetryCount+=1
if not %RetryCount%==30 goto CheckServer

echo There is no connection to server %Server%.
echo The network drive X: is not available.
goto :EOF

:MapDrive
echo Mapping network drive X: ...
%SystemRoot%\System32\net.exe use X: \\%Server%\share1 /persistent:no >nul

我必须补充一点,如果在运行防火墙的服务器上阻止ping到服务器,这个解决方案不起作用,因此工作站无法得到服务器ping的答案。

答案 2 :(得分:2)

您应该使用组策略首选项来映射网络驱动器,而不是批处理脚本,但是,如果您坚持,则在脚本中ping服务器不是正确的方法。

相反,您应该部署组策略设置:

"Computer Configuration" -> "Administrative Templates" -> "System" -> "Logon" -> "Always wait for the network at computer startup and logon"

这会强制计算机在运行启动/登录脚本之前等待网络启动。