如何从 Powershell 调用批处理脚本? [英] How to call batch script from Powershell?

查看:54
本文介绍了如何从 Powershell 调用批处理脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设置一堆环境变量的大批量脚本.我想从 powershell 调用那个批处理脚本,这样我就可以同时获得好处,即我的脚本和 powershell 设置的环境变量.

解决方案

这个想法来自这篇博文:没有什么能解决所有问题——PowerShell 和其他技术

这是我的脚本版本.它调用批处理文件(或任何本机命令)并传播其环境:

<小时>

更新:此脚本的改进和更好的测试版本在这里:Invoke-Environment.ps1

<预><代码><#.概要调用命令并导入其环境变量..描述它调用任何 cmd shell 命令(通常是一个配置批处理文件)和将其环境变量导入调用进程.命令输出是完全丢弃.如果命令退出代码不是 0,则失败.忽略退出代码使用call"命令..PARAMETER 命令任何 cmd shell 命令,通常是配置批处理文件..例子# 调用当前目录或系统路径下的Config.batInvoke-Environment Config.bat.例子# Visual Studio 环境:即使退出代码不为 0 也能工作Invoke-Environment '调用%VS100COMNTOOLS%vsvars32.bat"'.例子# 如果 vsvars32.bat 退出代码不为 0,则此命令失败调用环境 '"%VS100COMNTOOLS%vsvars32.bat"'#>参数([参数(强制=$true)] [字符串]$命令)cmd/c "$Command > nul 2>&1 && set" |.{过程{if ($_ -match '^([^=]+)=(.*)') {[System.Environment]::SetEnvironmentVariable($matches[1], $matches[2])}}}如果($ LASTEXITCODE){抛出命令‘$Command’:退出代码:$LASTEXITCODE"}

<小时>

附言以下是向 PowerShell 添加类似功能的建议:将点源概念扩展到 cmd 文件

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.

解决方案

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:


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. Here is the proposal to add similar capability to PowerShell: Extend dot sourcing concept to cmd files

这篇关于如何从 Powershell 调用批处理脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆