从 Windows 服务运行 VB 脚本

Posted

技术标签:

【中文标题】从 Windows 服务运行 VB 脚本【英文标题】:Run VB Script from Windows Service 【发布时间】:2013-09-18 11:44:10 【问题描述】:

我用 C# 编写了一个小型 Windows 服务,它执行 .BAT 和 .VBS 脚本。以下代码触发 .vbs 脚本:

string path = "C:\\Path\\To\\MyScript.vbs";
Process p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.CreateNoWindow = true;
p.StartInfo.WorkingDirectory = Environment.SystemDirectory;
p.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
p.StartInfo.Arguments = "/C C:\\Windows\\System32\\cscript.exe //Nologo \"" + path + "\"";
p.StartInfo.ErrorDialog = false;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += OutputDataReceived;
p.ErrorDataReceived += OutputDataReceived;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

try

p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit();

catch  // 

代码编译并运行,没有任何异常。但是,可能有问题,因为 VBS 脚本直到最后才执行。在脚本中,我打开一个 telnet 会话并输入一些命令。当我在 WinForms 应用程序中运行相同的代码和相同的脚本时,一切正常。

我认为问题是由我的服务引起的,该服务以本地系统运行。

有什么想法吗?

编辑

这是我的 VBScript:

set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run "cmd"
WScript.Sleep 1000 

WshShell.SendKeys "telnet 127.0.0.1 3000"
WshShell.SendKeys "ENTER"
WScript.Sleep 2000

WshShell.SendKeys "reboot application"
WshShell.SendKeys "ENTER"
WScript.Sleep 2000

由于某种原因,telnet 命令从未执行,但进程仍然以 exitcode '0' 结束...

【问题讨论】:

你调试了服务,看看会发生什么? 我做到了,但我没有收到异常或任何错误消息... 您可能不会收到异常,但 Process.Start() 可能会抛出错误代码。检查 process.ExitCode 你应该得到描述原因的整数。 感谢您的提示。该过程以“0”退出,因此看起来一切正常。我将添加上面的 VB 脚本以提供更多信息。 【参考方案1】:

知道了 - 当没有用户登录时,SendKeys 不起作用。代码本身运行良好。

【讨论】:

以上是关于从 Windows 服务运行 VB 脚本的主要内容,如果未能解决你的问题,请参考以下文章

Windows7 开机自启脚本

Windows7 开机自启脚本

如何停止在 Windows 中运行的 vb 脚本

运行python程序

PHP TCP 套接字连接限制 - Windows 服务器

无法在 Windows 7 x64 上使用 VB 脚本中的 CreateObject