Powershell Get-Process字符串作为名称

Thi*_*ngs 4 powershell

使用Get-Process时,如何将字符串用作-Name?

$program = "MyProgram"
Get-Process $program
Run Code Online (Sandbox Code Playgroud)

代替

Get-Process -MyProgram
Run Code Online (Sandbox Code Playgroud)

Aus*_*nch 5

无论如何,Powershell都会接受该名称。

Get-Process Firefox
Run Code Online (Sandbox Code Playgroud)

将返回所有正在运行的Firefox。同样,数组也可以工作:

Get-Process Firefox, iexplore
Run Code Online (Sandbox Code Playgroud)

要么

$Proc = @("Firefox","iexplore")
Get-Process $Proc
Run Code Online (Sandbox Code Playgroud)

显式声明一个数组,然后检查每个正在运行的进程。

当然,如前所述,您可以并且应该使用-Name来说明。但是什么都没有真正改变。该脚本仍应读取如下内容:

$Proc = @("Firefox","iexplore")
Get-Process -Name $Proc
Run Code Online (Sandbox Code Playgroud)

还有Where-Object方法:

Get-Process | Where-Object {$_.Name -eq "Firefox"}
Run Code Online (Sandbox Code Playgroud)

要对其进行“填充”,只需将对象通过管道传递到脚本块中。

对象在哪里:

PS C:\> Get-Process | Where-Object {$_.Name -eq "Firefox"} | fl $_.ID
Run Code Online (Sandbox Code Playgroud)

返回值:

Id      : 7516
Handles : 628
CPU     : 1154.1421983
Name    : firefox
Run Code Online (Sandbox Code Playgroud)

get-process $ Proc | FT ID,名称

将返回:

    Id Name
    -- ----
    7516 firefox
    12244 iexplore
    12640 iexplore
Run Code Online (Sandbox Code Playgroud)

或者,您最终可以使用前面提到的ForEach-Object,并遍历它们:

Get-Process $Proc | ForEach-Object {If($_.Path -contains "C:\Program Files*"){Write-host "Bad Directory"} else{ write-host "Safe"}}
Run Code Online (Sandbox Code Playgroud)

如果上面正在运行的.exe是从C:\ Program Files *运行的,则其写出“ Safe”,否则写出“ Bad Directory”。