问题
Everytime I tries to create a vbs file by batch , some lines are missing in the vbs file
@echo off
echo Function RunAsAdmin() >> 2.vbs
echo If WScript.Arguments.length = 0 Then >> 2.vbs
echo CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & _ >> 2.vbs
echo WScript.ScriptFullName & """" & "RunAsAdministrator""",,"runas", 1 >> 2.vbs
echo WScript.Quit >> 2.vbs
echo End If >> test.vbs
What do i need to keep these 2 lines when making a vbs file by batch?
echo CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & _ >> 2.vbs
echo WScript.ScriptFullName & """" & "RunAsAdministrator""",,"runas", 1 >> 2.vbs`
回答1:
Here is an alternative method that avoids the necessity of escaping:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Define constants here:
set "_VBS_FILE=%~dp02.vbs"
rem // Write to given output file:
> "%_VBS_FILE%" (
rem // Read all lines from this batch script that begin with `::::`:
for /F "delims=" %%V in ('findstr "^::::" "%~f0"') do (
rem // Store current line string:
set "VBS_LINE=%%V"
rem // Toggle delayed expansion to avoid loss of `!`:
setlocal EnableDelayedExpansion
rem // Return current line string with preceding `::::` removed:
echo(!VBS_LINE:*::::=!
endlocal
)
)
endlocal
exit /B
::This is the embedded VBS code section with each line preceded by `::::`:
::::Function RunAsAdmin()
::::If WScript.Arguments.length = 0 Then
:::: CreateObject("Shell.Application").ShellExecute "wscript.exe", """" & _
:::: WScript.ScriptFullName & """" & "RunAsAdministrator""", , "runas", 1
:::: WScript.Quit
::::End If
回答2:
Refer to this How to Escape Characters in batch file.
@echo off
Title Generate VBS File from batch script
Set "VBSFile=%~dpn0.vbs"
Call :Generate_VBS_File
Pause & Exit
REM -----------------------------------------------------------------------------
:Generate_VBS_File
>"%VBSFile%" (
echo Function RunAsAdmin(^)
echo If WScript.Arguments.length = 0 Then
echo CreateObject("Shell.Application"^).ShellExecute "wscript.exe", """" ^& _
echo WScript.ScriptFullName ^& """" ^& "RunAsAdministrator""",,"runas", 1
echo WScript.Quit
echo End If
echo End Function
)
Exit /B
REM -----------------------------------------------------------------------------
回答3:
You need to escape few special characters while echoing into files. The below code will do the trick for you.
echo CreateObject^("Shell.Application"^).ShellExecute "wscript.exe", """" ^& ^_ >>2.vbs
echo WScript.ScriptFullName ^& """" ^& "RunAsAdministrator""",,"runas",1 >>2.vbs
For example Use ^ to print the spcial characters like _,&. (Note: ^&-> will print &)
check the below link to know more about batch-escape characters.
https://www.robvanderwoude.com/escapechars.php
来源:https://stackoverflow.com/questions/62165309/how-can-i-create-a-vbs-file-by-batch-without-losing-those-lines