简体   繁体   English

如何使批处理文件将字符串作为命令运行?

[英]How do I make a batch file run strings as commands?

I want to make a batch file to circumvent some cmd problems on my computer, but for that I need to be able to take String user input and run it as a command. 我想制作一个批处理文件来规避计算机上的某些cmd问题,但是为此,我需要能够接受String用户输入并将其作为命令运行。

Basically what I want to be able to do is type in a command when the batch file asks for input, and have the computer run that command, similar to python's os module (class?) 基本上,我想做的是在批处理文件要求输入时键入命令,并让计算机运行该命令,类似于python的os模块(类?)。

Simply assign the string to a variable, then "execute" the variable as though it was a program 只需将字符串分配给变量,然后像执行程序一样“执行”该变量

eg 例如

set  myvar=ECHO Hello, World!
%myvar%

Use the set /p command to prompt for input. 使用set /p命令提示输入。 This command also displays a message. 此命令还会显示一条消息。 Example: 例:

@echo off
set "command=dir"
set /p "command=type in a command: "
echo.command is: %command%
echo.press any key or ^<CTRL+C^> to abort . . .
>nul pause
%command%

At its simplest, you want to use set /p to prompt for the command, setting an environment variable to the result, then simply expand the environment variable by itself and the OS will attempt to execute it as a command. 最简单的说,您想使用set /p提示输入命令,将环境变量设置为结果,然后简单地自行扩展环境变量,操作系统将尝试将其作为命令执行。

SET /P COMMAND=Command:
%COMMAND%

You can use the batch for loop, this works for me in the command prompt, but not the power shell: 您可以使用批处理循环,这在命令提示符下对我有用,但对于Power Shell不起作用:

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

C:\Users\Administrator>FOR /F "delims=" %i IN ('python -c "print('set wow=yep')"') DO set toexec=%i

C:\Users\Administrator>set toexec=set wow=yep

C:\Users\Administrator>%toexec%

C:\Users\Administrator>echo %wow%
yep

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM