2010-12-07 83 views

Respuesta

246

decir:

Wscript.Echo "Like this?" 

Si ejecuta que bajo wscript.exe (el controlador predeterminado para la extensión .vbs, así que lo que se obtiene si se hace doble clic en el guión) obtendrá un " Cuadro de diálogo "MessageBox" con su texto en él. Si ejecuta eso debajo de cscript.exe obtendrá salida en la ventana de su consola.

+18

+1 por la diferencia entre wscript abd CSCRIPT – KalenGi

+0

Se puede utilizar directamente en la wscript.exe la función 'MsgBox ("text") 'o' MsgBox (object.property) 'pero' Wscript.Echo' es más fácil de escribir. Gracias. – erm3nda

+11

Unintuitively para mí, 'WScript.Echo' * debe * usarse para si está ejecutando a través de' WScript' o 'CScript'. Es decir, there * is not * a 'CScript.Echo', en caso de que los futuros googlers se pregunten. (* Muy * feliz de que los msgboxes ya no estén [cuando se ejecutan con 'cscript']; gracias.) – ruffin

49

Sé que esto fue hace un tiempo, pero quizás esto ayude a los demás. Fue encontrado en Dragon-IT Scripts and Code Repository.

Puede hacer esto con lo siguiente y mantenerse alejado de las diferencias de cscript/wscript y le permite obtener la misma salida de consola que tendría un archivo por lotes. Esto puede ser útil si llama a VBS desde un archivo de proceso por lotes y necesita hacerlo sin problemas.

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." 
+4

Si la secuencia de comandos se inicia haciendo doble clic y, por lo tanto, se abre con wscript, la secuencia de comandos genera un mensaje de error: "Identificador no válido". –

+4

@Bernhard: Obtiene este error si ejecuta el script con wscript.exe. Wscript está orientado a Windows y no tiene secuencias de consola. Use cscript.exe en su lugar: http://technet.microsoft.com/en-us/library/bb490816.aspx –

+16

@BernhardHiller tiene un punto válido. El objetivo de esta respuesta es que usar stdout directamente evitaría las diferencias de CScript/WScript. Eso es incorrecto. Esta solución solo funciona con CScript.exe, por lo que no parece ser mucho más beneficioso que usar 'WScript.Echo'. De hecho, la diferencia se magnifica porque el script ya no se ejecutará bajo WScript. Es una técnica válida que tiene sus usos, por ejemplo, si uno necesita escribir en StdErr, pero en el contexto de esta respuesta, es engañoso. –

13

Solo necesita forzar cscript en lugar de wscript. Yo siempre uso esta plantilla. La función ForceConsole() ejecutará su vbs en cscript, también tiene un buen alias para imprimir y escanear texto.

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) 
+0

¿Estás seguro de que responde la [pregunta real] (http://stackoverflow.com/questions/4388879/vbscript-output-to-console)? – dakab

+0

Sí, solo llame a ForceConsole() y luego use printf() para imprimir texto en la consola de salida. También tiene otro alias para borrar la pantalla, escanear texto y esperar (dormir) – MadAntrax

4

me encontré con este post y volvió a un enfoque que utilicé hace algún tiempo, que es similar a la de @ MadAntrax.

La principal diferencia es que utiliza una clase VBScript definida por el usuario para ajustar toda la lógica para cambiar a CScript y enviar texto a la consola, por lo que hace que el script principal sea un poco más limpio.

Esto supone que su objetivo es transmitir la salida a la consola, en lugar de hacer que la salida vaya a cuadros de mensaje.

La clase cCONSOLE está debajo. Para usarlo, incluya la clase completa al final de su secuencia de comandos y luego ejecútelo justo al comienzo de la secuencia de comandos. He aquí un ejemplo:

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 

Aquí está el código para la clase 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 
Cuestiones relacionadas