3

我主要以这种方式将 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 输出的批处理脚本解决方案。

4

2 回答 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

于 2013-03-08T23:57:07.327 回答
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
)
于 2012-04-20T11:59:58.827 回答