简体   繁体   English

如何使用 powershell 从批处理脚本中运行批处理脚本?

[英]How do I run a batch script from within a batch script using powershell?

How do I call another batch script from within a batch script in powershell. In bash I used to get this done using the CALL keyword.如何从 powershell 中的批处理脚本中调用另一个批处理脚本。在 bash 中,我曾经使用 CALL 关键字完成此操作。 Is there an equivalent term for that in powershell?? powershell 中是否有对应的术语?

My problem is basically to start a dev environment using a batch file and then run some commands in that environment with the second batch file.我的问题基本上是使用批处理文件启动开发环境,然后使用第二个批处理文件在该环境中运行一些命令。

I tried using something like我尝试使用类似的东西

& Path\to\my\batchfile.bat -/c'command with spaces'

I was expecting it to open the dev environment with the batch file and run the provided command but it just keep runs the batch file and does not run the commands in it.我期待它用批处理文件打开开发环境并运行提供的命令,但它只是继续运行批处理文件而不运行其中的命令。

I'm assuming that your use case is as follows:假设您的用例如下:

  • You want to run batch file B.bat ,你想运行批处理文件B.bat
  • but batch file A.bat must run first , to set the environment that B.bat relies on.但必须运行批处理文件A.bat ,设置B.bat依赖的环境。
# "foo" and "bar" are sample arguments for B.bat
cmd /c 'c:\path\to\A.bat && c:\path\to\B.bat foo bar'

Note:笔记:

  • The call batch-file command is not needed in this case;在这种情况下不需要call batch-file 命令; call is only needed inside a batch file to call another batch file in a manner that returns control to the calling batch file. call只需要一个批处理文件中以将控制权返回给调用批处理文件的方式调用另一个批处理文件。

  • As long as A.bat sets its variables without using setlocal , B.bat will see those (environment) variables too.只要A.bat不使用setlocal的情况下设置其变量, B.bat也会看到那些(环境)变量。 [1] [1]


If A.bat does use setlocal - which limits the scope of variable definitions to that batch file [1] - and you're unable to modify A.bat to remove this constraint, there is no solution to your problem - irrespective of whether you call from cmd.exe or PowerShell. (That is, unless A.bat happens to be designed to accept a command line to execute as an argument .)如果A.bat确实使用setlocal - 它将 scope 的变量定义限制为该批处理文件[1] - 并且您无法修改A.bat以删除此约束,则您的问题没有解决方案 - 无论您是否从cmd.exe或 PowerShell 调用。(也就是说,除非A.bat恰好设计为接受命令行作为参数执行。)


[1] Unlike in PowerShell, in cmd.exe all variables are environment variables. [1] 与PowerShell不同, cmd.exe所有变量都是环境变量。 However, the optional setlocal command allows you to scope such variables to a given batch file (and, when paired with endlocal calls, even to parts of a batch file).但是,可选的setlocal命令允许您将 scope 这样的变量添加到给定的批处理文件中(并且,当与endlocal调用配对时,甚至可以添加到批处理文件的一部分)。 For help, run setlocal /?如需帮助,请运行setlocal /? and endlocal /?endlocal /? from cmd.exe .来自cmd.exe

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

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