Windows vbscript输出到控制台

Windows vbscript输出到控制台,windows,vbscript,console,output,Windows,Vbscript,Console,Output,使用vbscript将结果输出到控制台的命令或最快方式是什么?您的意思是: Wscript.Echo "Like this?" 如果在wscript.exe下运行该脚本(该.vbs扩展名的默认处理程序,因此双击该脚本将得到一个包含文本的“MessageBox”对话框)。如果在cscript.exe下运行,您将在控制台窗口中获得输出。这是在上找到的 您可以通过以下操作来实现这一点,并且远离cscript/wscript的差异,并允许您获得与批处理文件相同的控制台输出。如果您从批处理文件调用VBS

使用vbscript将结果输出到控制台的命令或最快方式是什么?

您的意思是:

Wscript.Echo "Like this?"
如果在
wscript.exe
下运行该脚本(该.vbs扩展名的默认处理程序,因此双击该脚本将得到一个包含文本的“MessageBox”对话框)。如果在
cscript.exe
下运行,您将在控制台窗口中获得输出。

这是在上找到的

您可以通过以下操作来实现这一点,并且远离cscript/wscript的差异,并允许您获得与批处理文件相同的控制台输出。如果您从批处理文件调用VBS,并且需要使其看起来无缝,这会有所帮助

Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."

您只需要强制cscript而不是wscript。我总是使用这个模板。函数ForceConsole()将把vbs执行到cscript中,您也有很好的别名来打印和扫描文本

 Set oWSH = CreateObject("WScript.Shell")
 vbsInterpreter = "cscript.exe"

 Call ForceConsole()

 Function printf(txt)
    WScript.StdOut.WriteLine txt
 End Function

 Function printl(txt)
    WScript.StdOut.Write txt
 End Function

 Function scanf()
    scanf = LCase(WScript.StdIn.ReadLine)
 End Function

 Function wait(n)
    WScript.Sleep Int(n * 1000)
 End Function

 Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
        WScript.Quit
    End If
 End Function

 Function cls()
    For i = 1 To 50
        printf ""
    Next
 End Function

 printf " _____ _ _           _____         _    _____         _     _   "
 printf "|  _  |_| |_ ___ ___|     |_ _ _ _| |  |   __|___ ___|_|___| |_ "
 printf "|     | | '_| . |   |   --| | | | . |  |__   |  _|  _| | . |  _|"
 printf "|__|__|_|_,_|___|_|_|_____|_____|___|  |_____|___|_| |_|  _|_|  "
 printf "                                                       |_|     v1.0"
 printl " Enter your name:"
 MyVar = scanf
 cls
 printf "Your name is: " & MyVar
 wait(5)

我看到了这篇文章,回到了我不久前使用的一种类似于@MadAntrax的方法

主要区别在于,它使用一个VBScript用户定义类来包装切换到CScript并将文本输出到控制台的所有逻辑,因此它使主脚本更简洁

这假设您的目标是将输出流式传输到控制台,而不是让输出进入消息框

下面是cCONSOLE类。要使用它,请在脚本末尾包含完整的类,然后在脚本开头实例化它。以下是一个例子:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here
下面是cCONSOLE类的代码

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

有五种方式可以将文本输出到控制台:

Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)

WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"
Echo将输出到控制台,但仅当使用cscript.exe启动脚本时。如果使用wscript.exe启动,它将输出到消息框

WScript.StdOut.Write和WScript.StdOut.WriteLine将始终输出到控制台


Write和StdOut.WriteLine也将始终输出到控制台。它需要额外的对象创建,但比WScript.Echo快约10%。

使用以下代码创建.vbs,这将打开主.vbs:

Set objShell = WScript.CreateObject("WScript.shell") 
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""
这是我的主要.vbs

Option Explicit
Dim i
for i = 1 To 5
     Wscript.Echo i
     Wscript.Sleep 5000
Next

如果通过双击启动脚本,然后使用wscript打开脚本,则脚本会导致错误消息:“无效句柄”。@Bernhard:如果使用wscript.exe运行脚本,则会出现此错误。Wscript面向windows,没有控制台流。改用cscript.exe:@BernhardHiller有一个有效点。这个答案的主旨是直接使用stdout可以避免CScript/WScript的差异。这是不正确的。此解决方案仍然只能在CScript.exe下工作,因此仅使用
WScript.Echo
似乎没有多大好处。事实上,差异被放大了,因为脚本将不再在WScript下运行。这是一种有效的技术,有它的用途,例如,如果一个人需要向StdErr写入,但是在这个答案的上下文中,它是误导性的。我只想强调一下这种方法相对于
WScript.Echo
的好处:
cscript//b foobar.vbs
在没有任何控制台输出的情况下运行
foobar.vbs
,但是通过Rob的方法,即使在将
\\b
传递到
cscript.exe
时,您也可以有输出,您可以直接在wscript.exe上使用函数
MsgBox(“text”)
MsgBox(object.property)
,但是
wscript.Echo
更易于编写。谢谢。对于我来说,不管您是通过
WScript
还是通过
CScript
运行,都必须使用
WScript.Echo
。也就是说,没有一个
CScript.Echo
,以防未来的谷歌搜索者怀疑。(非常高兴msgboxes(当使用
cscript
]运行时)不见了,但是;谢谢。)@GabrielStaples-不是股票
WScript.Echo
。我想,如果你想完全停留在WScript中,你可以做一些可怕的狡猾的事情,比如关闭另一个进程,对父进程执行“SendKeys”来关闭MessageBox。实际上,我刚刚找到了这个
弹出式方法。与echo非常相似,但允许您指定一个超时,在此超时后它将自动关闭弹出框。非常方便且易于使用:您确定回答了吗?是的,只需调用ForceConsole(),然后使用printf()在输出控制台中打印文本。另外,您还有其他别名来清除屏幕、扫描文本和等待(睡眠)这是有史以来最好的解决方案,谢谢,但只有“ForceConsole”功能很重要,“printf”和其他功能是完全不必要的,因为如果您强制关闭Wscript.exe实例上的当前脚本,然后运行当前脚本的新cscript.exe实例,然后Wscript.Echo将输出到该控制台实例。。。。。。正如在对之前答案的评论中所说,当使用wscript.exe执行时,这不起作用:还发现了关于GetStandardStream()与wscript.StdIn/.StdOut/.StdErr的解释:“简而言之,VBScript:a Desktop Quick Reference(第二版)”第298页说它“功能等效”。当你说“这不起作用”时,你能说明这五种方法中哪一种不起作用,以及你所说的不起作用是什么意思吗?