You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需管理员权限,如何在PowerShell中监控进程启动并关闭?

无需管理员权限的进程启动检测与终止方案

方案1:轮询检测(最简便无权限方案)

轮询是无需特殊权限的通用方案,通过定期检查目标进程是否存在,若存在则立即终止。虽然不像事件监听那样实时,但对于大多数场景足够高效,且完全不需要管理员权限。

示例代码:

$targetProcessName = "Process.exe"
$pollingIntervalMs = 500 # 每500毫秒检查一次,可根据需求调整

while ($true) {
    # 查找所有匹配的进程
    $processes = Get-Process -Name $targetProcessName -ErrorAction SilentlyContinue
    if ($processes) {
        foreach ($proc in $processes) {
            try {
                $proc.Kill()
                Write-Host "已终止进程: $($proc.Id)"
            }
            catch {
                Write-Warning "无法终止进程 $($proc.Id): $_"
            }
        }
    }
    Start-Sleep -Milliseconds $pollingIntervalMs
}

方案2:使用.NET的FileSystemWatcher(仅适用于从特定路径启动的进程)

如果目标进程仅从固定目录启动,可以用FileSystemWatcher监听该目录下的进程启动操作,结合进程检查来实现。这种方式比轮询更接近实时触发,但仅适用于特定路径的场景:

示例代码:

$targetProcessName = "Process.exe"
$watchPath = "C:\Path\To\Process\Directory" # 替换为进程所在目录

$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $watchPath
$watcher.Filter = $targetProcessName
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true

# 定义文件被启动时的处理逻辑
Register-ObjectEvent $watcher "Created" -Action {
    Start-Sleep -Milliseconds 100 # 等待进程完全启动
    $processes = Get-Process -Name $targetProcessName -ErrorAction SilentlyContinue
    if ($processes) {
        foreach ($proc in $processes) {
            try {
                $proc.Kill()
                Write-Host "已终止进程: $($proc.Id)"
            }
            catch {
                Write-Warning "无法终止进程 $($proc.Id): $_"
            }
        }
    }
} | Out-Null

# 保持脚本运行
Write-Host "正在监听进程启动...按Ctrl+C停止"
try {
    while ($true) { Start-Sleep -Seconds 1 }
}
finally {
    $watcher.Dispose()
    Unregister-Event -SourceIdentifier $event.SourceIdentifier
}

注意事项

  • 轮询方案的间隔时间可以根据需求调整,间隔越小越接近实时,但会占用更多系统资源。
  • 终止进程时,若目标进程以更高权限运行(比如管理员权限),普通用户权限下可能无法终止,但这是权限限制,与检测方式无关。

内容的提问来源于stack exchange,提问作者Digitality

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:25:23