如何在wmic输出中设置列顺序?

4

我通常将wmic用作Linux中的ps命令等效工具,例如:

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输出的批处理脚本解决方案。

2个回答

3
另一个选择是直接通过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


看起来非常强大。我喜欢它。我一定会试试这个。谢谢:D - Superole

2
一份简单的批处理文件可以完成这项工作(仅适用于您的情况)。
它通过搜索“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
)

这看起来不错,虽然有点复杂,即使我过去在让延迟扩展正常工作方面遇到了问题,但只要时间允许,我会给它一个机会的 ;) - Superole

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接