Get-Process in For Loop

Hi All,

On below code i am passing list of servers but the start time coming only for first server :frowning: Please help to resolve.

$Output = @()
$servers = Get-Content “D:\Scripts\servers.txt”
$servers | ForEach {
$Final = Get-WmiObject win32_service -ComputerName $_ -Filter “Name like ‘MSSQLSERVER’ or Name like ‘SQLSERVERAGENT’ or Name like ‘%MSSQL$%’ or Name like ‘%SQLAgent$%’ or Name like ‘ReportServer’
or Name like ‘SQLBrowser’ or Name like ‘MsDtsServer%’” -PipelineVariable Service |
Select-Object -Property @{Name=“Server_Name”;Expression={$.SystemName}}, @{Name=“Service_Name”;Expression={$.Caption}},
@{Name=“Service_Status”;Expression={$.State}}, @{label=‘Start_Time’;expression={(Get-Process -Id $Service.ProcessId).StartTime}},
.StartMode}}, @{Name=“Service_Log_on”;Expression={$.StartName}}
$Output += $Final
$Output | Export-CSV "D:\Reports\MSSQL_Service_Status
$(get-date -f MM-dd-yyyy).csv" -NoTypeInformation -Encoding UTF8

Hi, welcome to the forum :wave:

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and copying and pasting your code (we don’t have to faff about replacing curly quote marks to get things working).

How to format code on

The problem is because you’re running Get-Process on the same computer every time.

The quick fix is to specify the ComputerName parameter for Get-Process e.g.

@{label=‘Start_Time’;expression={(Get-Process -ComputerName $_ -Id $Service.ProcessId).StartTime}},

However, I recommend you take some time to refactor your code as you’re using deprecated commands and techniques.

1 Like

Hello Matt,

Thanks for your warm welcome :slight_smile:

I tried including ComputerName parameter for Get-Process post that output not coming for any server :frowning:

Sure I will work on modifying the code :slight_smile: