0

有谁知道为什么会发生以下情况并且有人有解决方法吗?

我正在努力捕获 mklink 命令输出(通过 cmd.exe mklink > out.txt)

如果 mklink 命令成功,输出将发送到 out.txt

例如:%comspec% /c mklink /d C:\Test C:\Windows > out.txt && notepad out.txt

但是,如果命令无效或失败,则不会将任何内容写入 out.txt

EG:(Run above command again失败,因为 C:\Test 已经存在)或

例如:%comspec% /c mklink > out.txt && notepad out.txt

我在 VBScript 中使用该命令,如果命令未成功完成,有人知道如何捕获 mklink 输出吗?

Set o_shell = CreateObject("Wscript.Shell")
Set o_fso = CreateObject("Scripting.FileSystemObject")
mklinkCommandOutput = GetCommandOutput("mklink /D ""C:\Test"" ""C:\Windows""")
WScript.echo mklinkCommandOutput

Function GetCommandOutput(runCmd)
  on error resume next
  Dim o_file, tempFile: tempFile = o_shell.ExpandEnvironmentStrings("%TEMP%") & "\tmpcmd.txt"

  ' Run command and write output to temp file
  o_shell.Run "%COMSPEC% /c " & runCmd & " > """ & tempFile & """", 0, 1

  ' Read command output from temp file
  Set o_file = o_fso.OpenTextFile(tempFile, 1)
  GetCommandOutput = o_file.ReadAll
  o_file.Close

  ' Delete temp file
  Set o_file = o_fso.GetFile(tempFile)
  o_file.Delete
End Function
4

2 回答 2

1

您是否考虑过使用“Exec”命令而不是运行命令并收集输出结果?

它不需要文件,而且更容易。

新代码

Function GetCommandOutput(runCmd)
  Dim WshShell, oExec
  Set WshShell = CreateObject("WScript.Shell")
  Set oExec    = WshShell.Exec("%COMSPEC% /c " & runCmd)
  GetCommandOutput = oExec.StdOut.ReadAll
End Function 

旧代码

Function GetCommandOutput(runCmd)
  on error resume next
  Dim o_file, tempFile: tempFile = o_shell.ExpandEnvironmentStrings("%TEMP%") & "\tmpcmd.txt"

  ' Run command and write output to temp file
  o_shell.Run "%COMSPEC% /c " & runCmd & " > """ & tempFile & """", 0, 1

  ' Read command output from temp file
  Set o_file = o_fso.OpenTextFile(tempFile, 1)
  GetCommandOutput = o_file.ReadAll
  o_file.Close

  ' Delete temp file
  Set o_file = o_fso.GetFile(tempFile)
  o_file.Delete
End Function 
于 2014-03-25T16:44:32.253 回答
1

(1)根据使用多个命令和条件处理符号&&,只有左边的命令成功,符号才会运行右边的命令。& 即使mlink失败,您也必须使用启动记事本。

(2) 虽然mlink 文档没有明确说明,但我假设mlink将其错误消息写入 Stderr(参见此处) - 就像dir.

证据:

dir 01.vbs
...
19.10.2012  11:29             2.588 01.vbs
...
(dir succeeded)

dir nix
...
File Not Found
(dir failed)

dir nix && echo nothing to see, because lefty failed
...
File Not Found
(dir failed, no output because of &&)

dir nix & echo much to see, although lefty failed
...
File Not Found
much to see, although lefty failed
(dir succeeded, echo done because of &)

(3) 要捕获mlink(rsp. dir) 的输出,无论它是否失败,并在记事本中显示结果(文件),您必须使用

dir 01.vbs 1> out.txt 2>&1 & notepad out.txt
dir nix 1> out.txt 2>&1 & notepad out.txt

将StdoutStderr 重定向到输出文件。

证据:

Dos 和记事本

于 2014-03-25T18:26:12.287 回答