我正试图从多个不同的数据中获得一个过程。在这个例子中,这个过程是Autodesk的DesktopConnector。有时Autodesk提供您在任务管理器( Task )中看到的名称,即自动桌面连接器()。有时,它们提供流程的实际名称,DesktopConnector.Applications.Tray.。有时他们提供可执行文件,desktopconnector.applications.tray.exe.因此,我想要一种基于其中任何一个返回流程对象的方法,然后我可以使用这些对象,例如停止进程,因为Autodesk太蠢了,无法产生停止进程本身的安装程序或卸载程序,除非您自己杀死进程,否则它们的更新安装程序和卸载程序就会失败。叹一口气。不管怎样..。这就是我所拥有的,为了验证我得到了我想要返回的对象,并了解每种方法所需的时间以及找不到任何东西所需的时间。
$strings = @('DesktopConnector.Applications.Tray','Autodesk Desktop Connector','desktopconnector.applications.tray.exe', 'Nope')
foreach ($string in $strings) {
(Measure-Command {
if (($process = (Get-Process -Name:$string -errorAction:SilentlyContinue)) -or
($process = ((Get-Process).Where({$PSItem.MainModule.FileVersionInfo.FileDescription -eq $string})) -or
($process = ((Get-Process).Where({$PSItem.Path.EndsWith($string)}))
))) {
Write-Host "$string $($process.id) " -NoNewLine
}
}).TotalSeconds
} 当我提供实际的进程名(第一个条件)时,我会得到一个预期的[System.Diagnostics.Process]。当我提供您在TaskManager (第二个条件)中看到的文件描述时,我会得到一个无用的[Bool],当我提供可执行文件(第三个条件)时,会得到一个错误,因为$PSItem.Path为null。那么,在后两个条件中,我遗漏了什么,这两个条件使我无法获得一个实际的过程?我知道这与使用.Where()有关,它返回我需要挖掘的PSObject,至少在第二个条件下是这样的。第三个条件,也是我搞砸的.Where()的谓词。但无论是哪种情况,我都无法找到解决办法。
根据Theo的评论,这是我所讨论的,似乎是关于性能,可读性和,你知道,实际的功能。
foreach ($string in $strings) {
(Measure-Command {
if (($process = (Get-Process -Name:$string -errorAction:SilentlyContinue)) -or
(Get-Process | Where-Object {$_.MainModule.FileVersionInfo.FileDescription -eq $string -or
$_.Path -like "*$string" })) {
Write-Host "$string $($process.id) " -NoNewLine
}
}).TotalSeconds
} 发布于 2022-06-18 13:07:05
我相信您使用Get-Process的次数太多了,每次迭代只能使用一次
试一试
$strings = 'DesktopConnector.Applications.Tray','Autodesk Desktop Connector','desktopconnector.applications.tray.exe', 'Nope'
foreach ($string in $strings) {
(Measure-Command {
$process = Get-Process |
Where-Object { $_.Name -eq $string -or
$_.MainModule.FileVersionInfo.FileDescription -eq $string -or
$_.Path -like "*$string" }
if ($process) { Write-Host "$string $($process.id) " -NoNewLine }
}).TotalSeconds
}我还使用$_.Path -like "*$string"而不是EndsWith()字符串方法,因为后者区分大小写,而-like不区分大小写。
https://stackoverflow.com/questions/72669395
复制相似问题