[英]Powershell Get-Process string as name
When using Get-Process how can I use a string as -Name? 使用Get-Process时如何使用字符串作为-Name?
$program = "MyProgram"
Get-Process $program
Instead of 代替
Get-Process -MyProgram
Powershell will accept the name, no matter what. 无论如何,Powershell都会接受这个名字。
Get-Process Firefox
Will return all running Firefox. 将返回所有正在运行的Firefox。 Likewise, arrays will work too:
同样,数组也可以工作:
Get-Process Firefox, iexplore
Or 要么
$Proc = @("Firefox","iexplore")
Get-Process $Proc
Declares an array explicitly, then checks for each running process. 显式声明一个数组,然后检查每个正在运行的进程。
Of course, as previously stated, you can and should use -Name for clarity. 当然,如前所述,您可以并且应该使用-Name来清楚。 But nothing really changes.
但没有什么真正改变。 The script should still read something like:
该脚本应该仍然是这样的:
$Proc = @("Firefox","iexplore")
Get-Process -Name $Proc
There is also the Where-Object approach: 还有Where-Object方法:
Get-Process | Where-Object {$_.Name -eq "Firefox"}
To do "stuff" with it, just pipe the objects into a script block. 要用它做“东西”,只需将对象传递到脚本块中。
Where-Object: 位置对象:
PS C:\> Get-Process | Where-Object {$_.Name -eq "Firefox"} | fl $_.ID
Returns: 返回:
Id : 7516
Handles : 628
CPU : 1154.1421983
Name : firefox
get-process $Proc | get-process $ Proc | FT ID, Name
FT ID,名称
Would return: 会回来:
Id Name
-- ----
7516 firefox
12244 iexplore
12640 iexplore
Or, you could finally use the ForEach-Object as mentioned, and loop through them: 或者,您最终可以使用所提到的ForEach-Object,并循环遍历它们:
Get-Process $Proc | ForEach-Object {If($_.Path -contains "C:\Program Files*"){Write-host "Bad Directory"} else{ write-host "Safe"}}
If the running .exe above is running from C:\\Program Files* then its writes out "Safe", otherwise it writes "Bad Directory". 如果上面运行的.exe从C:\\ Program Files *运行,则它写出“Safe”,否则写入“Bad Directory”。
Seems by popular agreement, the answer to your question is to provide a string array for the -Name
parameter of Get-Process
like so: 通过流行的协议似乎,你的问题的答案是为
Get-Process
的-Name
参数提供一个字符串数组,如下所示:
Get-Process -Name MyProgramA,MyProgramB
You can then loop through using the pipeline: 然后,您可以使用管道循环:
Get-Process -Name MyProgramA,MyProgramB | ForEach-Object {$_}
You can also use a variable: 您还可以使用变量:
Get-Process -Name $MyProgramStringArrray
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.