How to set column-order in wmic output?

batch-file, command-line, wmic

Solution

A simple batch file would do the job (only for your case).

It determines the start position of the second column by searching for `ProcessId`, and then each line will be reordered

@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
)

Problem

I use wmic mostly as a linux-ps-equivalent in this way: `wmic process where (name="java.exe") get processId, commandline` But the output columns are ordered alphabetically so I get: ``` CommandLine ProcessId java -cp ... some.Prog arg1 arg2 ... 2345 java -cp ... other.Prog arg1 arg2 ... 3456 ``` When what I want is: ``` ProcessId CommandLine 2345 java -cp .... some.Prog arg1 arg2 ... 3456 java -cp .... other.Prog arg1 arg2 ... ``` Which would be much more readable when the commandline is long. I'm thinking of writing a ps.bat to simplify the syntax for my use, so any batch script solutions for post-processing the wmic output are very welcome.

Original source