Array - foreach

i am trying to get the PID for services and i want to store that in an array

$services = get-service

foreach ($service in $services)

{

$pid = (gwmi win32_Service | where { $_.Name -eq $service}).ProcessID

}

How can i store all values in an array and retrive

July 24th, 2015 4:56am

Hi,

$services = Get-WmiObject win32_Service | Select-Object -Property Name,ProcessID
$services

$services contains now the service Name and the ProcessID


Free Windows Admin Tool Kit Click here and download it now
July 24th, 2015 5:37am

Hello,

$services = Get-WmiObject win32_Service | Select-Object -Property Name,DisplayName,ProcessID
$services #would give the Name DisplayName(for ease) and Process ID.
and

$services[0..9] gives first ten services.

Hope it helps!

Regards

July 24th, 2015 6:40am

how can i add the result that i get from foreach to an array
Free Windows Admin Tool Kit Click here and download it now
July 24th, 2015 7:13am

ProcessID are not unique. 

$RunningServices = @()

$WIN32Services = Get-WMIObject -Class WIN32_Service
ForEach ($WIN32Service in $WIN32Services) 
{
   IF ($Win32Service.ProcessID -NE 0) 
   {
       $RunningServices += $Win32Service
   }
}
$RunningServices.Count

82

July 24th, 2015 7:17am

$services = Get-WmiObject -Class Win32_Service

# Option 1
$array = $services.ProcessId

# Option 2
$array = foreach ($service in $services) {
    $service.ProcessId
}

# Option 3
$array = @()
foreach ($service in $services) {
    $array += $service.ProcessId
}

Free Windows Admin Tool Kit Click here and download it now
July 24th, 2015 7:38am

$services = @()

gwmi win32_Service | % {$services += $_.ProcessId}

wizend

July 24th, 2015 7:49am

Hi,

$services = Get-WmiObject win32_Service | Select-Object -Property Name,ProcessID
$services

$services contains now the service Name and the ProcessID


Free Windows Admin Tool Kit Click here and download it now
July 24th, 2015 9:31am

Why would anyone do this?  What is the purpose or requirement?

Easiest method to get an array of any property of a collection:

$pids=(gwmi win32_service ).processid

July 24th, 2015 10:23am

Hi,

  • For getting Service Name, ProcessID and State. Use below script which displays these details in Format-Table for services which are running

$PIDArray=Get-WmiObject -Class win32_service|select name, ProcessID, State |Where-Object {$_.State -eq "Running"}
$PIDArray| Format-Table

  • To get the PID alone use below script.

$PIDArray=Get-WmiObject -Class win32_service|select name, ProcessID, State |Where-Object {$_.State -eq "Running"}
$PIDArray.processID

Free Windows Admin Tool Kit Click here and download it now
July 25th, 2015 5:41pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics