变量包含在集合中

时间:2010-10-18 08:40:28

标签: windows batch-file if-statement

IF命令有一种方法可以在一组值中包含变量吗?

我的意思是:

  

IF %% i in(abc 123 opl)echo first set

     

IF %% i in(xyz 456 bnm)回显第二组

3 个答案:

答案 0 :(得分:0)

您可以使用for语句执行此操作。这是一个脚本,可以让你运行它:

myprog 456

并输出in set 2

@setlocal enableextensions enabledelayedexpansion
@echo off
for %%a in (abc 123 opl) do (
    if "x%%a"=="x%1" echo in set 1
)
for %%a in (xyz 456 bnm) do (
    if "x%%a"=="x%1" echo in set 2
)
@endlocal

答案 1 :(得分:0)

从命令行

C:\Users\preet>set val=99
C:\Users\preet>for %f in (100 99 21) do @if (%f)==(%val%) echo found it %f
found it 99

在批处理文件中

set val=99
for %%f in (100 99 21) do @if (%%f)==(%val%) echo found it %%f

答案 2 :(得分:0)

并且您也不仅限于在Windows计算机中批量处理。还有vbscript(和powershell)。以下是使用vbscript检查的方法

strVar = WScript.Arguments(0)
Set dictfirst = CreateObject("Scripting.Dictionary")
Set dictsecond = CreateObject("Scripting.Dictionary")
dictfirst.Add "abc",1
dictfirst.Add "123",1
dictfirst.Add "opl",1
dictsecond.Add "xyz",1
dictsecond.Add "456",1
dictsecond.Add "bnm",1
If dictfirst.Exists(strVar) Then
    WScript.Echo strVar & " exists in first set"
ElseIf dictsecond.Exists(strVar) Then
    WScript.Echo strVar & " exists in second set"
Else
    WScript.Echo strVar & " doesn't exists in either sets"  
End If 

用法:

C:\test>cscript //nologo test.vbs abc
abc exists in first set

C:\test>cscript //nologo test.vbs xyz
xyz exists in second set

C:\test>cscript //nologo test.vbs peter
peter doesn't exists in either sets