组合 PowerShell 命令以在 Java 程序中使用

组合 PowerShell 命令以在 Java 程序中使用

我正在编写一个 Java 程序,它将提取应用程序的进程相关日志。为此,我需要获取在特定位置创建的 Java 进程。我需要知道如何使用单个命令或可以在一行中传递的命令组合在 Windows 机器上获取此信息。

我做了一些研究,最终选择了 PowerShell。我使用两个单独的 PowerShell 命令获得了结果:

Powershell
Get-Process java| where {$_.path -like 'D:\ptc\Windchill_11.0\Java\jre\bin\java.exe'}

在此处输入图片描述

但是当我将两者结合起来时,没有得到任何结果:

Powershell ; Get-Process java ^| where {$_.path -like 'D:/ptc/Windchill_11.0/Java/jre/bin/java.exe'}

在此处输入图片描述

有人能帮我将两者结合起来吗,或者除了 PowerShell 之外还有其他选择吗?

答案1

好的,这意味着你对 PowerShell 还很陌生,还没有投入足够的时间来熟悉它,所以只能做一些猜测。这对你没有太大帮助。

不加速只会导致不必要的困惑、挫折、错误、坏习惯、误解等。因此,我建议你加速一下,这样你就可以减少/避免这样的经历。不过,任何学习都会有一些猜测/实验,因为这是事情的本质。;-}

不要将 Java 语法与 PowerShell 代码混合使用。PowerShell 中有许多保留字、变量,并且您必须以特定方式构建代码才能运行脚本、命令和 .exe。

PowerShell 中的分号不会使该行成为一行(管道一行)。这是同一行上的两个独立命令/代码块。它是一个语句终止符。

您必须已经处于 PowerShell 会话中才能运行 PowerShell 命令。

所以这...

Get-Process java| where {$_.path -like "D:\ptc\Windchill_11.0\Java\jre\bin\java.exe"}

... 有效,因为您显然已经启动了 PowerShell,并手动输入了此命令。

这..

 Powershell ; Get-Process java ^| where {$_.path -like 'D:/ptc/Windchill_11.0/Java/jre/bin/java.exe'} enter image description here

…失败,因为在执行 PowerShell 命令之前您不在 PowerShell 会话中。

看: PowerShell.exe 命令行帮助

# EXAMPLES

# Create a new PowerShell session and load a saved console file
PowerShell -PSConsoleFile sqlsnapin.psc1

# Create a new PowerShell V2 session with text input, XML output, and no logo
PowerShell -Version 2.0 -NoLogo -InputFormat text -OutputFormat XML

# Execute a PowerShell Command in a session
PowerShell -Command "Get-EventLog -LogName security"

# Run a script block in a session
PowerShell -Command {Get-EventLog -LogName security}

# An alternate way to run a command in a new session
PowerShell -Command "& {Get-EventLog -LogName security}"

# To use the -EncodedCommand parameter:
$command = "dir 'c:\program files' "
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand

那么,你的是……

PowerShell -Command "Get-Process java ^ | where {$_.path -like 'D:/ptc/Windchill_11.0/Java/jre/bin/java.exe'}"

PowerShell:运行可执行文件

使用 PowerShell 时,了解引用规则至关重要。

PowerShell 引号 – 展开还是不展开,这是个问题

PowerShell 引用规则的故事

再次强调,由于您是新手,请花必要的时间进行以下操作:

...并使用所有免费/免费资源全部通过网络. 就像 MS TechNetWindows PowerShell 生存指南

相关内容