变量%ProgramFiles(x86)%未按批处理文件的预期设置或返回

问题描述 投票:-1回答:3

给定以下批处理文件:

@echo off
echo %programfiles(x86)%
set test=%programfiles(x86)%
echo %test%
if 0==0 ( 
    set test2=%programfiles(x86)%
)
echo %test2%

输出返回为:

C:\Program Files (x86)
C:\Program Files (x86)
C:\Program Files (x86

注意最后一行的缺失括号。

任何人都可以解释发生了什么或我做错了什么?

windows batch-file variables
3个回答
1
投票

%programfiles(x86)%扩大时,它变成C:\Program Files (x86)

你的if命令变成了

if 0==0 (
    set test2=C:\Program Files (x86)
)

解析器然后将其读作

if 0==0 (
    set test2=C:\Program Files (x86
)

这可以通过以下方式防止

if 0==0 (
    set "test2=%programfiles(x86)%"
)

“”分隔符确保将确切的字符串作为参数传递给SET命令。

在一行上输入单个)在CMD环境中不会产生错误响应。


1
投票

%programfiles(x86)%被解析为C:\Program Files (x86)导致你的if语句关闭(路径的最后一个字符是),它关闭了if)

您可以尝试添加引号以指示其是字符串的一部分:

if 0==0 ( 
    set "test2=%programfiles(x86)%"
)

0
投票

在将)修改为@echo off并在命令提示符窗口中运行此批处理文件时,可以看到缺少右括号@echo ON的原因。

具有IF条件的命令行和以(开头的整个命令块在对以下单个命令行执行IF命令之前进行预处理:

if 0 == 0 (set test2=C:\Program Files (x86 )

在预处理阶段用%programfiles(x86)%替换C:\Program Files (x86)后找到Windows命令解释器,右括号)不在双引号字符串中。所以对于Windows命令解释器)C:\Program Files (x86)中没有用双引号字符串括起来标记命令块的结尾。没有匹配的)的额外(被忽略了。结果是test2只被分配了C:\Program Files (x86

解决方案是用双引号括起命令SET的参数,如How to set environment variables with spaces?Why is no string output with 'echo %var%' after using 'set var = text' on command line?的答案中所述

@echo off
echo %ProgramFiles(x86)%
set "test=%ProgramFiles(x86)%"
echo %test%
if 0 == 0 ( 
    set "test2=%ProgramFiles(x86)%"
)
echo %test2%
© www.soinside.com 2019 - 2024. All rights reserved.