Force a VBS to run using cscript instead of wscript

前端 未结 5 1573
予麋鹿
予麋鹿 2020-12-29 07:42

What is the stackoverflow approved (and hence correct) method to force a VBS to run using cscript instead of wscript - irrespective of what the user tries?

A quick G

5条回答
  •  难免孤独
    2020-12-29 08:16

    My Lord, what unadulterated rubbish. It makes me cry to see such cruddy coding (no offense to anybody, lol). Seriously, though, here's my 2 pence:

    Sub forceCScriptExecution
        Dim Arg, Str
        If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
            For Each Arg In WScript.Arguments
                If InStr( Arg, " " ) Then Arg = """" & Arg & """"
                Str = Str & " " & Arg
            Next
            CreateObject( "WScript.Shell" ).Run _
                "cscript //nologo """ & _
                WScript.ScriptFullName & _
                """ " & Str
            WScript.Quit
        End If
    End Sub
    forceCScriptExecution
    

    It handles arguments, AND checks for spaces in said arguments -- so that in the case of a filename passed to the original script instance that contained spaces, it wouldn't get "tokenized" when passed to cscript.exe.

    Only thing it doesn't do is test for StdIn (e.g., in the case where someone piped something to the script via the command line, but forgot to use "cscript script.vbs") -- but if it was executed by WScript.exe, WScript.StdIn's methods all return Invalid Handle errors, so there's no way to test that anyway.

    Feel free to let me know if there's a way to "break" this; I'm willing to improve it if necessary.

提交回复
热议问题