如何从Powershell的调用批处理脚本? [英] How to call batch script from Powershell?
问题描述
我有一个很大的批处理脚本用于设置一堆的环境变量。
我想打电话从PowerShell会在批处理脚本,这样我可以得到我的脚本和PowerShell设置这两个即enviorment变量的好处。
I have one big batch script which sets bunch of environment variables. I want to call that batch script from powershell, that way I can get benefits of both i.e. enviorment variable set by my script and powershell.
推荐答案
这个想法来源于此博客文章:<一href=\"http://www.leeholmes.com/blog/2006/05/11/nothing-solves-everything-%e2%80%93-powershell-and-other-technologies/\"相对=nofollow>没有解决一切问题 - PowerShell和其他技术
The idea comes from this blog post: Nothing solves everything – PowerShell and other technologies
下面是我这个脚本的版本。它调用批处理文件(或任何本地的命令),并传播它的环境:
Here is my version of this script. It calls a batch file (or any native command) and propagates its environment:
更新:改进和这个脚本的测试更好的版本是在这里:调用-Environment.ps1
UPDATE: Improved and better tested version of this script is here: Invoke-Environment.ps1
<#
.SYNOPSIS
Invokes a command and imports its environment variables.
.DESCRIPTION
It invokes any cmd shell command (normally a configuration batch file) and
imports its environment variables to the calling process. Command output is
discarded completely. It fails if the command exit code is not 0. To ignore
the exit code use the 'call' command.
.PARAMETER Command
Any cmd shell command, normally a configuration batch file.
.EXAMPLE
# Invokes Config.bat in the current directory or the system path
Invoke-Environment Config.bat
.EXAMPLE
# Visual Studio environment: works even if exit code is not 0
Invoke-Environment 'call "%VS100COMNTOOLS%\vsvars32.bat"'
.EXAMPLE
# This command fails if vsvars32.bat exit code is not 0
Invoke-Environment '"%VS100COMNTOOLS%\vsvars32.bat"'
#>
param
(
[Parameter(Mandatory=$true)] [string]
$Command
)
cmd /c "$Command > nul 2>&1 && set" | .{process{
if ($_ -match '^([^=]+)=(.*)') {
[System.Environment]::SetEnvironmentVariable($matches[1], $matches[2])
}
}}
if ($LASTEXITCODE) {
throw "Command '$Command': exit code: $LASTEXITCODE"
}
P.S。下面是类似的功能添加到PowerShell中建议:<一href=\"https://connect.microsoft.com/PowerShell/feedback/details/564858/extend-dot-sourcing-concept-to-cmd-files\"相对=nofollow>扩展点的采购理念,以CMD文件
这篇关于如何从Powershell的调用批处理脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!