简体   繁体   English

如何在Powershell中使用get-process结果填充数组

[英]How do I populate an array with get-process results in powershell

I'm trying to write a PS1 script that: 我正在尝试编写一个PS1脚本:
1. takes a computer name and a process name 1.以计算机名和进程名
2. Shows you all PIDs and processes that match your search 2.显示与您的搜索相匹配的所有PID和进程
3. Asks you what PID you want to kill. 3.询问您要杀死的PID。 (I haven't included this part of the code) (我没有包含这部分代码)

I need help on the $processInfo array. 我需要有关$ processInfo数组的帮助。 I want to be able to look through each of the processes and show the name and ID. 我希望能够浏览每个过程并显示名称和ID。 and then I'll know what PID to kill after that. 然后我将知道要杀死的PID是什么。

So if I search "App*" how can I output to the format of: 因此,如果我搜索“ App *”,如何输出为以下格式:

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

Here's what I have so far 这是我到目前为止的

# 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 can take wildcards in the Name parameter. Get-Process可以在Name参数中使用通配符。 So you just need to loop over the object and output the properties you are looking for. 因此,您只需要遍历对象并输出所需的属性。

# 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}

You could also get rid of all of the Read-Host and Write-Host for a more PowerShelly feel. 您还可以摆脱所有Read-HostWrite-Host ,从而获得更多PowerShell感。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM