感谢马蒂亚斯和塞巴斯蒂安.有了您的宝贵输入,我想出了以下函数来获取进程ID.
function Get-ProcessByPort {
param(
[int]$Port
)
$services = netsh http show servicestate
$positionSession=0
$countSession=0
$countProcess=0
[bool] $takeNextPID=0
$processId=$null
foreach ($s in $services){
if ($takeNextPID -eq 1) {
$processId=$s
break
}
if ($s -match 'Server session ID') {
$countSession++
}
if ($s -match "HTTP://LOCALHOST:$Port/") {
$positionSession=$countSession
}
if ($s -match 'Process IDs:') {
$countProcess++
}
if ($positionSession -gt 0) {
if ($countProcess -eq $positionSession) {
$takeNextPID=1
}
}
}
if (-not ([string]::IsNullOrEmpty($processId)))
{
$processId=$processId.Trim()
}
return $processId
}