簡體   English   中英

如何使用for命令從文本文件捕獲數據並將其設置為變量(Windows命令提示符)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM