有人知道为什么会发生以下情况并且有人有解决方法吗?
我正在捕捉mklink命令输出(通过cmd.exe mklink> out.txt)
如果mklink命令成功,输出将被发送到out.txt
E.G:%comspec% /c mklink /d C:\Test C:\Windows > out.txt && notepad out.txt
但是,如果命令无效或失败,则不会将任何内容写入out.txt
E.G:Run above command again
(因为C:\ Test已经存在而失败)或
E.G:%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
答案 0 :(得分: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
答案 1 :(得分:1)
(1)根据Using multiple commands and conditional processing symbols,符号&&
仅在左侧的命令成功时才在右侧运行命令。你必须使用&
即使mlink
失败,也要开始记事本。
(2)虽然mlink docs没有明确说明,但我认为mlink
将其错误消息写入Stderr(请参阅here) - 就像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
将Stdout 和 Stderr重定向到输出文件。
证据: