PowerShell远程机器特定进程线程数、关联用户名查询及线程数最高用户获取脚本开发求助
Hey there! Let's break down how to build this PowerShell script for your remote machine query. You're already on the right track with your local process script—we just need to adapt it for remote access, add username retrieval, and calculate the user with the highest total thread count.
Step 1: Remote Process & User Data Collection
First, we'll use Get-CimInstance (more reliable for remote management than Get-Process in many environments) to fetch process info from the remote machine. This method lets us easily get both thread counts and process owners via WMI:
# Configure your target machine and process name here $remoteComputer = "YourRemotePCName" $targetProcessName = "chrome.exe" # Replace with your specific process # Fetch remote process details with thread count and owner username $remoteProcessData = Get-CimInstance -ComputerName $remoteComputer -ClassName Win32_Process -Filter "Name='$targetProcessName'" | ForEach-Object { # Get the process owner's domain and username $owner = $_.GetOwner() [PSCustomObject]@{ ProcessName = $_.Name ThreadCount = $_.ThreadCount FullUsername = "$($owner.Domain)\$($owner.User)" } }
Step 2: Calculate User with Highest Total Threads
Next, we'll group the data by username, sum up their total threads, and sort to find the top user:
# Group by username and calculate total threads per user $userThreadSummary = $remoteProcessData | Group-Object -Property FullUsername | ForEach-Object { [PSCustomObject]@{ Username = $_.Name TotalThreads = ($_.Group | Measure-Object -Property ThreadCount -Sum).Sum NumberOfProcesses = $_.Count } } # Sort by total threads descending and grab the top user $topUser = $userThreadSummary | Sort-Object -Property TotalThreads -Descending | Select-Object -First 1 # Output the results Write-Host "User with highest thread count for $targetProcessName on $remoteComputer:" $topUser
Key Notes & Troubleshooting
- Permissions: Make sure your account has administrative (or WMI access) rights on the remote machine.
- Remote Setup: The remote machine needs WinRM enabled (run
Enable-PSRemoting -Forceas admin on the remote PC if it's not set up). - Specific Process vs All Processes: If you want to check all processes instead of a specific one, just remove the
-Filter "Name='$targetProcessName'"parameter fromGet-CimInstance.
Bonus: Quick Single-Process Thread Leader
If you just want the single process instance with the most threads (and its user), skip the grouping and sort directly:
$remoteProcessData | Sort-Object -Property ThreadCount -Descending | Select-Object FullUsername, ProcessName, ThreadCount -First 1
内容的提问来源于stack exchange,提问作者Matt

