使用 cscript 输出 "ipconfig /all" 但文本文件为空

Using cscript to output "ipconfig /all" but text file is blank

我正在尝试提取 ipconfig /all 输出并将其放入文本文件中。我创建了一个小的 VBScript,它可以毫无问题地运行 ipconfig。然后我在另一个 VBScript 中调用它。所有这些都在运行,但输出文本文件仍然是空的,并且在 ipconfig.vbs 运行后主 VBScript 似乎没有写任何东西。

这是来自主要 .vbs 脚本的示例:

' Pulling network config
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile("C:\Users\dsadmin\Desktop\LogNet\network_config.txt", 8)
set objFile = objFSO.OpenTextFile("C:\Users\dsadmin\Desktop\LogNet\network_config.txt")
objShell.Run("cscript //nologo C:\Users\dsadmin\Downloads\ipconfig.vbs >C:\Users\dsadmin\Desktop\LogNet\network_config.txt")

这是它调用的脚本 (ipconfig.vbs):

Set objShell = CreateObject("WScript.Shell")
objShell.Run("ipconfig /all")

说到改头换面,我没主意了。

重定向 (>) 是 CMD 的内置功能。您需要运行 CMD 中的语句才能使用它:

objShell.Run "%COMSPEC% /c cscript //NoLogo C:\ipconfig.vbs >C:\network_config.txt"

当然,您需要确保第二个脚本首先写入 STDOUT,正如 指出的那样。

如果您的第二个脚本所做的只是 运行ning ipconfig /all,那么将其包装在一个单独的脚本中就没有多大意义了。就直接运行吧:

objShell.Run "%COMSPEC% /c ipconfig /all >C:\network_config.txt"

这种方法有两个问题

  1. 作为 @Ansgar-Wiechers > 重定向是 CMD 的一部分。

  2. 重定向工作后,您必须从执行的命令中检索标准输出并将其重定向到 cscript.exe 输出。不幸的是 .Run() 不提供对标准输出流的访问,您必须使用 .Exec() 代替。

这里是一个例子(假设所有文件都在同一方向,但可以修改);

' Pulling network config
Set objShell = CreateObject("WScript.Shell")
Call objShell.Run("%COMSPEC% /c cscript //nologo ipconfig.vbs > network_config.txt")

在ipconfig.vbs

Set objShell = CreateObject("WScript.Shell")
Set exec = objShell.Exec("ipconfig /all")
'Redirect output from executed command to the script output.
Call WScript.StdOut.Write(exec.StdOut.ReadAll)

输出为network_config.txt

Windows IP Configuration

   Host Name . . . . . . . . . . . . : 
   Primary Dns Suffix  . . . . . . . : 
   Node Type . . . . . . . . . . . . : 
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No
   DNS Suffix Search List. . . . . . : 

Wireless LAN adapter Local Area Connection* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . : 
   Description . . . . . . . . . . . : Microsoft Wi-Fi Direct Virtual Adapter
   Physical Address. . . . . . . . . : 
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
...

... 已截断以提高可读性并删除了敏感数据