[英]How to set an env variable with multiline file content in windows command prompt
[英]How can i capture data using the for command from a text file and set it as a variable (windows command prompt)
情况
使用Diskpart,我可以获得详细的磁盘信息,如下所示:
Microsoft DiskPart version 10.0.17763.1
Copyright (C) Microsoft Corporation.
On computer: PC
Disk 1 is now the selected disk.
Samsung SSD 960 EVO 500GB
Disk ID: {00000}
Type : NVMe
Status : Online
Path : 0
Target : 0
LUN ID : 0
Location Path : PCIROOT(0)#PCI(1D00)#PCI(0000)#NVME(P00T00L00)
Current Read-only State : No
Read-only : No
Boot Disk : Yes
Pagefile Disk : Yes
Hibernation File Disk : No
Crashdump Disk : Yes
Clustered Disk : No
Volume ### Ltr Label Fs Type Size Status Info
---------- --- ----------- ----- ---------- ------- --------- --------
Leaving DiskPart...
我要捕获的文本是“ Samsung SSD 960 EVO 500GB”。显然,当我在具有不同驱动器的系统上运行此信息时,此信息将更改,因此它可能是Western Digital或Seagate驱动器等。
我在考虑使用:
for /f "skip=7 delims=" %g in (disk1.txt) do set disk1=%g
但是,这捕获了下面的所有内容,最后的数据位(“ Leave DiskPart ...”)作为变量存储。 不是第一个值。 我怎样才能解决这个问题? 一定有我没想到的简单事情。
如果您不愿意从命令行运行它,我认为这是您唯一的选择。
set "disk1=" & for /f "skip=7 delims=" %g in (disk1.txt) do IF NOT DEFINED disk1 set "disk1=%g"
但是,由于您用批处理文件标记了此问题,因此可以使用GOTO命令。
for /f "skip=7 delims=" %%g in (disk1.txt) do (set "disk1=%%g" & goto done)
:done
您是否愿意直接访问源代码并跳过文本处理?
FOR /F "delims=" %%s IN ('powershell -NoLogo -NoProfile -Command "(Get-CimInstance -ClassName CIM_DiskDrive).Model"') DO (SET "DISK1=%%s")
好主意,@ LotPings。
FOR /F "delims=" %%s IN ('powershell -NoLogo -NoProfile -Command "(Get-Disk).FriendlyName"') DO (SET "DISK1=%%s")
鉴于这可能返回一个数组,请使用-Number
参数选择哪个数组。
FOR /F "delims=" %%s IN ('powershell -NoLogo -NoProfile -Command "(Get-Disk -Number 0).FriendlyName"') DO (SET "DISK1=%%s")
一旦开始编写PowerShell脚本而不是.bat文件,这将变得更加容易。 显然,PowerShell是Microsoft设置的过程。
$disk1 = (Get-Disk -Number 0).FriendlyName
您还可以利用WMIC
来执行此操作,与DiskPart
方法不同,该方法不需要以管理员身份运行,也不需要将输出写入文件并重新读回以进行解析 :
@For /F "Skip=1Delims=" %%A In ('WMIC DiskDrive Where "Index=1" Get Model')Do @For /F Tokens^=* %%B In ("%%A")Do @Set "_=%%B"
要检查它是否有效,请在其下面添加以下行:
@Set _&Pause
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.