【问题标题】:How do I populate an array with get-process results in powershell如何在powershell中使用get-process结果填充数组
【发布时间】:2018-08-15 19:52:43
【问题描述】:

我正在尝试编写一个 PS1 脚本:
1. 取一个计算机名和一个进程名
2. 显示与您的搜索匹配的所有 PID 和进程
3.询问您要杀死的PID。 (我没有包含这部分代码)

我需要有关 $processInfo 数组的帮助。 我希望能够查看每个进程并显示名称和 ID。然后我会知道在那之后要杀死什么PID。

所以如果我搜索“App*”,我该如何输出格式:

Process ID: 1000 Name: Apple
Process ID: 2000 Name: Appster
Process ID: 3000 Name: AppSample

这是我目前所拥有的

# Look up a computer, and a process, and then 
$computerName = Read-Host "Enter the FQDN of the target computer:"

# Enter the name of the process you're looking for. Wildcard searching is asterix
$processSearch = Read-Host "Enter the process name to look for:"

# Create a process array with PID, Name, and Runpath
$processInfo = (
    processID = get-process -ComputerName $computerName -Name $processSearch | select -expand ID,
    processName = get-process -ComputerName $computerName -Name $processSearch |select -expand Name,
    processPath = get-process -ComputerName $computerName -Name $processSearch |select -expand Path
)

# Display all of the processes and IDs that match your search
foreach($id in $processInfo){
    write-host Process ID: $id.processID Name: $id.processName
}

【问题讨论】:

  • 不要多次致电Get-Process。调用一次并保存结果 - 它已经是一个数组。然后让你的 foreach 遍历每个对象。更好的是,试试这个:$process = Get-Process -ComputerName $computerName -Name $processSearch | Out-GridView -OutputMode Single。或者按照@BenH 的建议去做。
  • 您无需展开它们即可获得所有详细信息。像$processinfo = get-process -ComputerName $computername -name $processsearch | select id,name,path 这样的东西。另外请将 write-host 更改为 write-output

标签: powershell


【解决方案1】:

Get-Process 可以在Name 参数中使用通配符。所以你只需要遍历对象并输出你正在寻找的属性。

# Look up a computer, and a process, and then 
$ComputerName = Read-Host "Enter the FQDN of the target computer:"

# Enter the name of the process you're looking for. Wildcard searching is asterix
$ProcessSearch = Read-Host "Enter the process name to look for:"

Get-Process -ComputerName $ComputerName -Name "$ProcessSearch*" | ForEach-Object {Write-Host Process ID: $_.ID Name: $_.ProcessName}

您也可以get rid of all of the Read-Host and Write-Host 以获得更强大的感觉。

Get-Process -ComputerName $ComputerName -Name "$ProcessSearch*" | Select-Object ID,ProcessName

【讨论】:

    猜你喜欢
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-26
    • 2013-12-19
    • 2015-03-02
    • 2020-01-21
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多