我尝试写一些东西来在批处理脚本中获取硬盘索引,命令提示符下的命令运行良好
wmic diskdrive where "model like '%st%' and size > 300000000000" get index,model
它回来了
Index Model
1 ST1000DM010-2EP102
但是当我在批处理脚本中使用它时,它返回“没有可用的实例”:
@echo off
for /f "usebackq skip=1" %%a in (`wmic diskdrive where "model like '%st%' and size > 300000000000" get index`) do echo %%a
pause
脚本结果
No Instance(s) Available.
顺便说一句,如果有更好的方法在批处理脚本中获取硬盘索引。
wmic diskdrive where "model like '%st%' and size > 300000000000" get /format:csv
@Compo, 命令执行结果如下
Node,Availability,BytesPerSector,Capabilities,CapabilityDescriptions,Caption,CompressionMethod,ConfigManagerErrorCode,ConfigManagerUserConfig,CreationClassName,DefaultBlockSize,Description,DeviceID,ErrorCleared,ErrorDescription,ErrorMethodology,FirmwareRevision,Index,InstallDate,InterfaceType,LastErrorCode,Manufacturer,MaxBlockSize,MaxMediaSize,MediaLoaded,MediaType,MinBlockSize,Model,Name,NeedsCleaning,NumberOfMediaSupported,Partitions,PNPDeviceID,PowerManagementCapabilities,PowerManagementSupported,SCSIBus,SCSILogicalUnit,SCSIPort,SCSITargetId,SectorsPerTrack,SerialNumber,Signature,Size,Status,StatusInfo,SystemCreationClassName,SystemName,TotalCylinders,TotalHeads,TotalSectors,TotalTracks,TracksPerCylinder
W0400966,,512,{3;4},{Random Access;Supports Writing},ST1000DM010-2EP102,,0,FALSE,Win32_DiskDrive,,Disk drive,\\.\PHYSICALDRIVE1,,,,CC46,1,,IDE,,(Standard disk drives),,,TRUE,Fixed hard disk media,,ST1000DM010-2EP102,\\.\PHYSICALDRIVE1,,,3,SCSI\DISK&VEN_ST1000DM&PROD_010-2EP102\4&BFDEFCD&0&000100,,,0,0,0,1,63, ZN1PYMST,3140447416,1000202273280,OK,,Win32_ComputerSystem,W0400966,121601,255,1953520065,31008255,255
在您提交的第一个工作命令提示符示例中,您使用的是 WMI LIKE 运算符,
%
表示 0 个或多个字符串字符。
百分比字符
%
是批处理文件中的特殊字符,因此任何文字都需要转义。百分号的转义字符是另一个百分号。
因此,为了在批处理文件中重现该命令提示符代码,您可以使用:
wmic diskdrive where "model like '%%st%%' and size > 300000000000" get index,model
然而,您要匹配的模型子串实际上以
ST
开头,它不包括任何位置的st
这两个字符。出于这个原因,您的代码应该一直使用 ST%%
作为您的模式。
%SystemRoot%\System32\wbem\WMIC.exe DiskDrive Where "Model Like 'ST%%' And Size > 300000000000" Get Index, Model
随后,您编辑了您的问题,向我们表明您并不是真的想重现命令提示符代码,而是想将其作为
For
带括号的命令运行。为了在批处理文件中执行此操作,您需要转义未加引号的逗号:
… In ('%SystemRoot%\System32\wbem\WMIC.exe DiskDrive Where "Model Like 'ST%%' And Size > 300000000000" Get Index^, Model 2^>NUL') Do …
你会在上面注意到,如果 WMIC 命令报告
No Instance(s) Available.
,我决定将该输出发送到 NUL 设备(随后什么都不传递到循环的 Do
部分)。
很明显,您根本不想报告模型字符串,而是隔离其输出的特定子字符串,即仅索引号。为此,我建议您使用返回值定义一个变量。
@Echo Off
SetLocal EnableExtensions DisableDelayedExpansion
Set "Index="
For /F "Tokens=2 Delims==" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
DiskDrive Where "Model Like 'ST%%' And Size > 300000000000" Get Index
/Value 2^>NUL') Do For %%H In (%%G) Do Set "Index=%%H"
If Not Defined Index GoTo :EOF
Rem Your code continues below here.
Echo Your Disk Index is %Index%
Pause
我在
Rem
ark 下方添加了几行,仅用于演示目的。随意根据您的特定任务需要更换那些。