Reputation: 941
I have bunch of servers and I want to check if I can connect to them with RDP. I have 2000 servers so I wanted to automate it.
I'm not very familiar with PowerShell, here is what I have:
list.txt:
ip1
ip2
ip3
...
ipn
Here is my code. I loop on each ips, connect, check if the connection was successfull and try to close it.
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()
}
Remote Desktop Connection opens and connect. The if statements works too. But I cannot manage to kill my fresh Remote Desktop Connection nammed " - Remote Desktop Connection". It seems like $app
is empty.
I tried also:
Stop-Process -processname "$_*"
EDIT
I do not want to check if the remote machine has RDP on (check port with Test-NetConnection -Port 53 -ComputerName $_
), but if a specific user has acces to the remote server.
Workaround
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
}
This work if you are sure to only have one RDP connection on the machine you are working on. For me i'm connected in RDP to that machine... So it will have 2 mstsc
process running. For the moment it never killed my session, only the newer ones. But if someone else go in RDP on the machine, it could break everything.
Upvotes: 3
Views: 2121
Reputation: 19684
You can validate that $app
is properly populated by using wmi:
$app = Get-WmiObject -Filter 'CommandLine LIKE "%$_%"' -Class Win32_Process
...
$app.Terminate()
Alternatively, you can utilize Start-Process
with -PassThru
to launch mstsc.exe
and assign $app
, and then when you're done: $app | Stop-Process
In action:
$app = Start-Process -FilePath C:\Windows\System32\mstsc.exe -ArgumentList "/v:$_" -PassThru
...
$app | Stop-Process
Upvotes: 3