你可以試試下面的代碼片段:
@echo off
setlocal EnableDelayedExpansion
set /P "user=write UserName="
set /P "password=write Password="
> "a.csv" (
for /F "usebackq tokens=*" %%a in ("ip.txt") do (
set "lineString="
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% computersystem get Name /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% computersystem get Model /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% computersystem get totalphysicalmemory /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% cpu get Name /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% path Win32_VideoController get Name /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% os get Caption /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% csproduct get identifyingnumber /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% desktopmonitor get screenheight /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
for /F "tokens=1,* delims==" %%A in ('wmic /node:%%a /user:%user% /password:%password% desktopmonitor get screenwidth /value') do for /F "delims=" %%Z in ("%%B") do set "lineString=!lineString!,%%Z"
if defined lineString echo(!lineString:~1!
)
)
endlocal
exit /B
的wmic
輸出存儲到,
- 分隔字符串中的變量lineString
。爲了捕獲命令的輸出,for /F
循環是完美的。但是,wmic
命令會生成Unicode輸出,因此需要兩個嵌套的for /F
循環才能進行適當的Unicode/ANSI轉換;單個循環會在字符串中留下孤立的尾隨回車符。
的wmic
輸出格式已從/format:table
改變爲/value
得到這樣的輸出:Caption=Microsoft Windows 7 Enterprise
,所以for /F
環可以採取=
作爲分隔符,並得到所需的值。
除了這一切,我也改變了以下內容:
在代碼中,你分別重定向每一個循環迭代的輸出。爲避免這種情況,()
已放在(最外面的)for /F
循環中,因此整個數據被重定向到a.csv
。因此,重定向操作符已從追加類型>>
更改爲(over)寫入類型>
。
Delayed expansion已啓用哪些修改和()
之間讀取內for
迴路或代碼塊的變量(lineString
)時是必需的。
對於同一個類,您可以獲得多個值,如:'wmic/node:%% a/user:%user%/ password:%password%computersystem get Name,Model/format:table'按字母順序排列) – aschipfl
是的,但是當我把它放在一個csv文件中時我需要它以逗號分隔,所以我可以將它導入另一個程序來組織 – TmCookieMonster
在純批處理腳本中,這不是微不足道的,因爲'wmic'產生Unicode輸出,有些麻煩;然而,你可以在for/F循環中執行_every_'wmic'命令行,以便循環解析輸出:'for/F「tokens = 1,* delims ==」%% A('wmic OS GET Caption/VALUE')do for/F「delims =」%% Z in(「%% B」)do echo(%% Z'(有兩個循環:外部分離感興趣的值,內部分離消除潛在的在Unicode/ANSI轉換過程中由外部字符留下的孤立尾部回車字符) – aschipfl