提问人:Enigma86 提问时间:12/29/2020 更新时间:12/30/2020 访问量:139
批处理 – 带有错误级别条件的 Findstr,引号?[复制]
Batch – Findstr with error level condition, quotes? [duplicate]
问:
我有一个批处理文件脚本,我编写了该脚本作为连接到网络共享的接口。在这一点上,它非常简单。它有一个我的共享列表,我想将其与正在使用的网络共享进行比较,并在找到该共享时禁用该共享作为选项。以下代码片段是 for 循环的一部分,该循环循环访问列表中的共享数并列出它们。
setlocal enabledelayedexpansion
set list[0]="\\xxx.xxx.x.xx\photo"
set list[1]="\\xxx.xxx.x.xx\photo 2"
for /l %%n in (0,1,2) do (
rem wmic netuse get remotename |findstr /C:!list[%%n]!
rem if %errorlevel% neq 0 do(command 1) else (command 2)
echo %%n !list[%%n]!
)
为了测试问题,删除了上述内容。
这里的想法是使用条件来赶上比赛。股票用双引号呼应。例如,如果安装了照片,则照片和照片 2 都将匹配,这是不可取的。
由于共享具有相似的名称并添加了带空格的数字,因此我需要准确地比较字符串,因此我尝试了开关,但这根本不起作用。不确定带双引号的条目是否会干扰。删除列表中的双引号会产生一个错误,即无法打开空格后的数字。我是否以正确的方式处理这个问题?rem
if %errorlevel%
findstr /x
答:
1赞
Stephan
12/29/2020
#1
我可以假设一种稍微不同的方法吗?
@echo off
setlocal enabledelayedexpansion
set "list[0]=\\xxx.xxx.x.xx\photo"
set "list[1]=\\xxx.xxx.x.xx\photo 2"
for /l %%n in (0,1,2) do (
net use |findstr ilc:" !list[%%n]! " >nul && (
echo found "!list[%%n]!", do command1
) || (
echo no match for "!list[%%n]!" do command2
)
)
对代码的更改:
- 使用而不是 作为输出 Unicode,我们必须处理它。而且速度要快得多。
net use
wmic
wmic
net use
- 使用条件运算符,而不是
&&
||
errorlevel
- 变得更加安全,并且
findstr
- discarded 的输出。
findstr
- 更正了语法,使其不包含值的引号。
set
评论
%errorlevel%
%var%
%errorlevel%
delayedexpansion
!var!
if [not] errorlevel n
if the errorlevel is [not] "n" OR GREATER THAN "n"
for /F "tokens=2 delims==" %%i in ('set list[') do %SystemRoot%\System32\wbem\wmic.exe netuse get remotename | %SystemRoot%\System32\findstr.exe /C:%%i && command 2 || command 1
findstr /?
/G
/V
/L