powershell - 多个重复发生的过程

标签 powershell cmd powershell-2.0 nmap

我正在测试一些域以及它们在发生异常事件时提醒我的能力。我正在使用 nmap 扫描域以查找开放端口。下面的脚本打开一个新的 cmd 窗口并运行 nmap。我搜索进程 ID 并检查进程(cmd)是否仍在运行。扫描结束后,它将再次运行 nmap 扫描。

function nmaptest {
    $prog1="cmd"
    $params1=@("/C";"nmap.exe -Pn -sX 192.168.1.0/24")
    Start-Process -Verb runas $prog1 $params1 #starts
}

while(1 -eq 1){
    nmaptest
    $processes = get-process $prog1 | out-string
    $sp = $processes.Split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
    $procid = $sp[22]
    echo $procid

    while(get-process -id $procid){ }
}

这工作正常。我需要帮助的是并行执行此过程 8 次。 (如果可能的话)

最佳答案

好吧,除非您启动 CMD 有任何特定原因(例如需要查看输出),否则我建议改用作业。如果它们仍在运行,则易于管理和测试。

$jobs = @()
$sx = '192.168.1.0/24', 'range2', 'etc'
For ($i = 0; $i -lt $sx.Length; $i++) { $jobs += Start-Job { nmap.exe -Pn -sX $sx[i] } }

while ($true) {
    For ($i = 0; $i -lt $sx.Length; $i++) { 
        if ($jobs[i].State -eq "Completed" {
            Write-Output ("Completed job for " + $sx[i])
            Receive-Job $jobs[i]
            $jobs[i] = Start-Job { nmap.exe -Pn -sX $sx[i] }
        } 
    }
    Start-Sleep -s 5
}

关于powershell - 多个重复发生的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32398485/

相关文章:

java - 当我从 Java 打开 CMD 时,无法更改目录

python - 获取主板上内存插槽总数的方法

excel - 使用powershell从excel工作簿中删除工作表

在windows上编译运行flex程序

selenium - 如何关闭 Selenium Grid2 服务器?

regex - 将get-content cmdlet与-replace选项一起使用以替换csv中的事件,无法弄清楚如何

powershell - 启动进程不适用于 VSIXInstaller.exe

powershell - 使用powershell中的 split 方法获取前两位数字

powershell - 高级语法

powershell - PowerShell-Get-Credential解码密码?