简体   繁体   中英

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

I'm trying to write a PS1 script that:
1. takes a computer name and a process name
2. Shows you all PIDs and processes that match your search
3. Asks you what PID you want to kill. (I haven't included this part of the code)

I need help on the $processInfo array. I want to be able to look through each of the processes and show the name and ID. and then I'll know what PID to kill after that.

So if I search "App*" how can I output to the format of:

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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