Garbage char returned by Shell.StdOut.ReadAll

342 views Asked by At

Here is my code

Set objFSO = CreateObject("Scripting.FileSystemObject")

a = "@echo off && " & _
"pushd ""\\xxxxx.local\cfs\Development\Docs\Baseline"" &&" & _
"cls &&" & _
"dir /b /a-d &&" & _
"popd"

Set objShell = CreateObject("WScript.Shell").Exec("%comspec% /c " & a)
execStdOut = objShell.StdOut.ReadAll()
msgbox execStdOut

Basically I am trying to run Dir command on a network drive. It works fine, but the only issue is that the output contains a garbage character in the beginning. Not sure why?

Output

If I run the same steps in a batch file, the output is correct

enter image description here

2

There are 2 answers

2
rojo On BEST ANSWER

The answer to your question is that cls is being captured by the StdOut stream and interpreted as an extended character. Get rid of it. You don't need it.

Just so I feel like I've done something, here's the script rewritten as a batch + JScript hybrid. Save it with a .bat extension if you want to mess with it.

@if (@CodeSection == @Batch) @then

@echo off
setlocal

if "%~1"=="shell" (
    pushd "\\xxxxx.local\cfs\Development\Docs\Baseline"
    dir /b /a-d
    popd
    goto :EOF
)

cscript /nologo /e:JScript "%~f0"

goto :EOF
@end // end batch / begin JScript

var oSH = WSH.CreateObject('Wscript.Shell'),
    proc = oSH.Exec("cmd /c " + WSH.ScriptFullName + " shell");

oSH.popup(proc.StdOut.ReadAll());

As an added bonus, here's the same thing with a lovely "ding" noise added.

@if (@CodeSection == @Batch) @then

@echo off
setlocal

if "%~1"=="shell" (
    pushd "\\xxxxx.local\cfs\Development\Docs\Baseline"
    dir /b /a-d
    popd
    goto :EOF
)

cscript /nologo /e:JScript "%~f0"

goto :EOF
@end // end batch / begin JScript

var oSH = WSH.CreateObject('Wscript.Shell'),
    noise = WSH.CreateObject('WMPlayer.OCX.7'),
    proc = oSH.Exec("cmd /c " + WSH.ScriptFullName + " shell");

with (noise) {
    URL = oSH.Environment('Process')('SYSTEMROOT') + '\\Media\\Windows Exclamation.wav';
    Controls.play();
}

oSH.popup(proc.StdOut.ReadAll());
0
JosefZ On

The character is ASCII control character Line Feed 0x0A, a residuum of CLI cls command. Just omit the "cls &&" & _ line in your code as follows:

a = "@echo off && " & _
  "pushd ""\\xxxxx.local\cfs\Development\Docs\Baseline"" &&" & _
  "dir /b /a-d &&" & _
  "popd"