Search code examples
powershellcsvforeachscripting

Process or program running on specific machines using powershell


i'm new in the world of programming and on powershell scripting. My collegue gave me this command to run to identify if YES or NO the program PROGRAM.EXE is running on a list of computers. But i found it hard to do it on over 50 machines. I want to run it using powershell the forEach function. This is what i've done already but i don't have the expected result. Usually he uses this > tasklist /s COMPUTER1 /svc /fi "IMAGENAME eq PROGRAM.EXE") This gave several result and when the program is installed, it return the name, and the PID of the program , else it says aucune tƒche en service ne correspond aux critŠres sp‚cifi‚s. I want to use it but with powershell, with the list of computers.

This is what i've tried but i feelled bloked

$postes = @('COMPUTER1', 'COMPUTER2', 'COMPUTER3')

Foreach($element in $postes) 
{ 
    $( tasklist /s $($element) /svc /fi "IMAGENAME eq PROGRAM.EXE")
}

I expect to switch case the result if or no the program is installed. But the result is not controlable that way. Can someone help please.

Thank you all.


Solution

  • Depending on the amount of remote computers you want to query you could check if you can reach each individual computer in a loop and only query the online ones ... something like this:

    $computerList = Get-Content -Path 'c:\files\mycomputer.txt'
    $NomProgramme = 'XWin_MobaX'
    
    $data = 
    foreach ($computer in $computerList) {
        if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
            Invoke-Command -ComputerName $computer -HideComputerName -ScriptBlock {
                [PSCustomObject]@{
                    Computer       = $ENV:COMPUTERNAME 
                    Online         = $True
                    ProgramRunning = if (Get-Process -Name $USING:NomProgramme -ErrorAction SilentlyContinue) { $True } else { $false }  
                }
            } |
                Select-Object -ExcludeProperty RunspaceId
        }
        else {
            [PSCustomObject]@{
                Computer       = $computer 
                Online         = $false
                ProgramRunning = 'n/a'  
            }
        }
    } 
    $data | Format-Table -AutoSize
    $data | Export-Csv -Path c:\files\Services.csv -NoTypeInformation
    

    If you have really a lot of computers to check you may switch to PowerShell version 7 and use its builtin ability to run commands in parallel with Foreach-Object -Parallel You can read more about here: Get-Help Foreach-Object