首页 > 解决方案 > 批处理脚本回显另一个批处理脚本

问题描述

如何在批处理文件中回显(创建)另一个批处理文件以在 Windows 启动中运行并在运行后将其删除?[实际使用一个批处理脚本尝试 WSl 2 安装程序]

我试过这个,

@echo off
:: BatchGotAdmin
// asking one time admin priv code  here
@echo off
title wsl setup Part 1 ! 


dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

// and here is my another batch to need echo correctly in C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\ for run after reboot  
 
(echo @echo off^
:: BatchGotAdmin
// admin priv for  seconf batch  

@echo off
title wsl setup part 2 !

//other steps for download kernel and set default wsl version here

echo "Setup Finished, Deleting this bat" && del C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\wsl-part2.bat && pause
) > "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\wsl-part2.bat"


//First batch again for asking reboot now or later


:PROMPT
SET /P REBOOTNOW=Do you want reboot now second script will run after reboot (Y/[N])?
IF /I "%REBOOTNOW%" NEQ "N" GOTO END

shutdown -r


:END
endlocal

但是我卡住了 dism 命令循环(因为 echo 不理解它是一个字符串)并且只回显到目标文件

@echo off:: BatchGotAdmin
Requesting administrative privileges...

标签: windowsbatch-fileecho

解决方案


尽管我有相反的评论,但如果您希望使用如此复杂的方法来执行此操作,以下是执行此操作的一般语法:

(   Echo @Echo Off
    Echo Rem BatchGotAdmin
    Echo // admin priv for second batch  
    Echo Title WSL Setup Part 2.
    Echo // other steps for download kernel and set default WSL version here
    Echo Echo Setup Finished, deleting this script.
    Echo (GoTo^) 2^>Nul ^& Del "%%~f0"
) 1> "%ProgramData%\Microsoft\Windows\Start Menu\Programs\StartUp\wsl-part2.cmd"

您应该注意到我已经将自删除命令更改为更有效和更实用的命令。它决定这样做是因为它向您表明,使用此方法,您需要使用脱字符号转义有问题的字符(包括与号、重定向符号、管道和右括号)。您还需要%通过将字符加倍来转义字符。


推荐阅读