我有很多服务器,我想检查是否可以使用 RDP 连接到它们。我有 2000 台服务器,所以我想实现自动化。
我对 PowerShell 不太熟悉,以下是我所掌握的:
列表.txt:
ip1
ip2
ip3
...
ipn
这是我的代码。我在每个 ip 上循环、连接、检查连接是否成功并尝试关闭它。
Get-Content C:\Users\MyUser\Documents\computers2.txt |
ForEach-Object{
cmdkey /generic:TERMSRV/$_ /user:MyUser /pass:MyPassWord
mstsc /v:$_
Start-Sleep 90
$app = Get-Process -processname "$_*"
if (Get-winevent -comp $_ -FilterHashtable @{Logname='security'; ID=4624; starttime=(get-date).addMinutes(-10)} | where {$_.properties[8].value -eq 10 -and $_.properties[5].value -eq 'MyUser'}) {
"$_" >> C:\Users\MyUser\Documents\valid.txt
}
$app.Kill()
}
远程桌面连接打开并连接。 if 语句也有效。但我无法杀死名为“-远程桌面连接”的新远程桌面连接。这好像是$app
是空的。
我也尝试过:
Stop-Process -processname "$_*"
EDIT
我不想检查远程计算机是否开启了 RDP(使用以下命令检查端口)Test-NetConnection -Port 53 -ComputerName $_
),但如果特定用户有权访问远程服务器。
解决方法
Get-Content C:\Users\MyUser\Documents\computers2.txt |
ForEach-Object{
cmdkey /generic:TERMSRV/$_ /user:MyUser /pass:MyPassWord
mstsc /v:$_
Write-Host "Sleeping for 90 sec"
Start-Sleep 90
if (Get-winevent -comp $_ -FilterHashtable @{Logname='security'; ID=4624; starttime=(get-date).addMinutes(-10)} | where {$_.properties[8].value -eq 10 -and $_.properties[5].value -eq 'MyUser'}) {
"$_" >> C:\Users\MyUser\Documents\result.txt
}
Get-Process | Where-Object { $_.Name -eq "mstsc" } | Select-Object -First 1 | Stop-Process
}
如果您确定您正在使用的计算机上只有一个 RDP 连接,则此操作有效。对我来说,我通过 RDP 连接到该机器...所以它将有 2mstsc
进程运行。目前它还没有杀死我的会话,只是更新了新的会话。但如果其他人在机器上使用 RDP,则可能会破坏一切。