Does anybody know why the below happens and does anybody have a workaround?
I'm strugging to capture mklink command output (via cmd.exe mklink > out.txt)
Output is sent to out.txt fine if the mklink command is successful
E.G: %comspec% /c mklink /d C:\Test C:\Windows > out.txt && notepad out.txt
However if the command is invalid, or fails, then nothing will be written to out.txt
E.G: Run above command again
(fails because C:\Test already exists) or
E.G: %comspec% /c mklink > out.txt && notepad out.txt
I'm using the command in VBScript, does anybody know how to capture the mklink output if the command isn't completed successfully?
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
(1) According to Using multiple commands and conditional processing symbols, the symbol &&
runs the command on the right only if the command on the left succeeds. You must use &
to start notepad even when the mlink
fails.
(2) While the mlink docs don't say so explicitly, I assume that mlink
writes its error message to Stderr (see here) - just like dir
.
Evidence:
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) To capture the output of mlink
(rsp. dir
) whether it fails or not and to display the result (file) in notepad, you have to use
dir 01.vbs 1> out.txt 2>&1 & notepad out.txt
dir nix 1> out.txt 2>&1 & notepad out.txt
to redirect Stdout and Stderr to the output file.
Evidence: