windows 如何使批处理文件将字符串作为命令运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15658475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make a batch file run strings as commands?
提问by pipsqueaker117
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 模块(类?)
回答by Magoo
Simply assign the string to a variable, then "execute" the variable as though it was a program
只需将字符串分配给一个变量,然后像程序一样“执行”该变量
eg
例如
set myvar=ECHO Hello, World!
%myvar%
回答by Endoro
Use the set /p
command to prompt for input. This command also displays a message. Example:
使用set /p
命令提示输入。此命令还会显示一条消息。例子:
@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%
回答by Nate Hekman
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%
回答by srossross
You can use the batch for loop, this works for me in the command prompt, but not the power shell:
您可以使用批处理 for 循环,这在命令提示符下对我有用,但在 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