2010-10-18 67 views
0

IF命令有一種方法將變量包含在一組值中?集合中包含的變量

我的意思是:

IF %% i的(ABC 123 OPL)回聲首先設置

IF %% i的(XYZ 456 BNM)回聲第二設定

回答

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 
+0

好的謝謝,那是我更喜歡的簡單方式 – aemme 2010-10-18 09:31:14

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 
+0

我看到了它的工作原理,但我想給變量從批處理文件中傳遞給for循環,所以我想放%% a = 123在代碼的開頭。你寫的命令是「帶修飾符的變量」? – aemme 2010-10-18 09:18:20

+0

然後,您只需在腳本的開頭放置'set xx = 7',並使用'%xx%'而不是'%1'。 – paxdiablo 2010-10-18 09:56:31

+0

非常感謝。您使用的參數是FOR命令的修飾符,我試圖在Windows幫助中查找它,但我沒有找到它。 – aemme 2010-10-18 10:08:51

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