Powershell Get-Process 字符串作为名称

标签 powershell

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

$program = "MyProgram"
Get-Process $program

代替
Get-Process -MyProgram

最佳答案

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

Get-Process Firefox

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

或者
$Proc = @("Firefox","iexplore")
Get-Process $Proc

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

当然,如前所述,为了清楚起见,您可以而且应该使用 -Name。但没有什么真正改变。该脚本仍应读取如下内容:
$Proc = @("Firefox","iexplore")
Get-Process -Name $Proc

还有 Where-Object 方法:
Get-Process | Where-Object {$_.Name -eq "Firefox"}

要使用它做“东西”,只需将对象通过管道传输到脚本块中。

哪里-对象:
PS C:\> Get-Process | Where-Object {$_.Name -eq "Firefox"} | fl $_.ID

返回:
Id      : 7516
Handles : 628
CPU     : 1154.1421983
Name    : firefox

获取进程 $Proc | FT ID、姓名

会返回:
    Id Name
    -- ----
    7516 firefox
    12244 iexplore
    12640 iexplore

或者,您最终可以使用前面提到的 ForEach-Object,并循环遍历它们:
Get-Process $Proc | ForEach-Object {If($_.Path -contains "C:\Program Files*"){Write-host "Bad Directory"} else{ write-host "Safe"}}

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

关于Powershell Get-Process 字符串作为名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678870/

相关文章:

windows - 使用 Powershell 或命令行在 Windows 中创建压缩文件夹

arrays - 匹配数组时Powershell使用通配符

arrays - 比较对象返回无效结果

powershell - powershell命令中的等效/s/V"/qn

Powershell:如何将空正文传递给 Send-MailMessage?

powershell - Powershell和Visio出现错误

xml - 使用 PowerShell 将 Excel 文件保存为 XML

azure - 在 Powershell 中安装 Az 模块时出错 - 程序包 'Az.Accounts' 无法安装

powershell - 删除 PowerShell DSC 配置

powershell - 从批处理文件运行时,Powershell 中的 Get-Filehash SHA256 加密会删除最后 4 位数字