2012-04-20 53 views
0

我使用WMIC主要是作爲Linux-PS-相當於這樣:如何在wmic輸出中設置列順序?

wmic process where (name="java.exe") get processId, commandline

但輸出列字母順序排列的,所以我得到:

CommandLine       ProcessId 
java -cp ... some.Prog arg1 arg2 ... 2345 
java -cp ... other.Prog arg1 arg2 ... 3456 

當我要的是:

ProcessId CommandLine 
2345  java -cp .... some.Prog arg1 arg2 ... 
3456  java -cp .... other.Prog arg1 arg2 ... 

這將是更加易讀當命令行很長。

我正在考慮編寫一個ps.bat來簡化我的使用語法,因此任何批處理腳本解決方案都可以對後期處理wmic輸出進行處理,非常受歡迎。

回答

1

一個簡單的批處理文件可以完成這項工作(僅適用於您的情況)。

它通過搜索ProcessId確定第二列的起始位置,然後將每個線將被重新排序

@echo off 
setlocal EnableDelayedExpansion 
set "first=1" 
for /F "usebackq delims=" %%a in (`"wmic process where (name="cmd.exe") get processId, commandline"`) DO (
    set "line=%%a" 
    if defined first (
     call :ProcessHeader %%a 
     set "first=" 
     setlocal DisableDelayedExpansion 
    ) ELSE (
     call :ProcessLine 
    ) 
) 
exit /b 

:ProcessHeader line 
set "line=%*" 
set "line=!line:ProcessID=#!" 
call :strlen col0Length line 
set /a col1Start=col0Length-1 
exit /b 

:ProcessLine 
setlocal EnableDelayedExpansion 
set "line=!line:~0,-1!" 
if defined line (
    set "col0=!line:~0,%col1Start%!" 
    set "col1=!line:~%col1Start%!" 
    echo(!col1!!col0! 
) 
Endlocal 
exit /b 

:strlen <resultVar> <stringVar> 
( 
    setlocal EnableDelayedExpansion 
    set "s=!%~2!#" 
    set "len=0" 
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
     if "!s:~%%P,1!" NEQ "" ( 
      set /a "len+=%%P" 
      set "s=!s:~%%P!" 
     ) 
    ) 
) 
( 
    endlocal 
    set "%~1=%len%" 
    exit /b 
) 
+0

這看起來不錯,雖然有點複雜,即使我在過去的延遲擴展工作中遇到問題,我會盡快給這個機會;) – Superole 2012-04-26 09:30:47

+1

簡單的批處理?微軟!!!!!!! – 2017-12-19 14:34:42

1

另一種選擇是直接訪問通過VBS的WMI的Win32_Process的SQL表,而不使用WMIC。然後,您可以精確管理哪些列,列順序及其輸出格式。

下面是CSV輸出的VBS代碼:processList.vbs

' === Direct access to Win32_Process data === 
' ------------------------------------------- 
Set WshShell = WScript.CreateObject("WScript.Shell") 
Set locator = CreateObject("WbemScripting.SWbemLocator") 
Set service = locator.ConnectServer() 
Set processes = service.ExecQuery ("select ProcessId,CommandLine,KernelModeTime,UserModeTime from Win32_Process") 

For Each process in processes 
    Return = process.GetOwner(strNameOfUser) 
    wscript.echo process.ProcessId & "," & process.KernelModeTime & "," & process.UserModeTime & "," & strNameOfUser & "," & process.CommandLine 
Next 

Set WSHShell = Nothing 

命令行用法:cscript //NoLogo processList.vbs

Win32_Process的列列表:http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394372(v=vs.85).aspx

原始的Java代碼在這裏:http://www.rgagnon.com/javadetails/java-0593.html

+0

看起來非常強大。我喜歡。我會明確地嘗試一下。謝謝:D – Superole 2013-03-12 15:13:36